为什么 Stata return “unknown function +inrange()”?

Why does Stata return “unknown function +inrange()”?

我正在学习 Stata 编程,阅读 Stata 编程简介,第二版

第四章中有代码generate一个变量测试其他变量是否满足逻辑条件,代码如下:

foreach v of varlist child1-child12{
        local n_school "`n_school' + inrange(`v', 1, 5)"
    }
    gen n_school = `n_school'

当我更改此代码以适合我自己的数据时,

foreach v of varlist qp605_s_1-qp605_s_5 {
        local n_med  "`n_med' + inrange(`v', 1, 5)"
    }
    gen n_med = `n_med'

其中 qp605_s_1 的值范围为 1 到 17,然后 Stata returns:

. foreach v of varlist qp605_s_1-qp605_s_5 {
  2.         local n_med "`n_med' + inrange(`v', 1, 5)"
  3. }

. gen n_med = `n_med'
unknown function +inrange()
r(133);

知道这段代码有什么问题吗?

我知道我哪里错了

本地的n_med开头是+,所以我改成:

local n_med 0
foreach v of varlist qp605_s_1-qp605_s_5{
    local n_med "`n_med' + inrange(`v', 1, 5)"
}
gen n_med = `n_med',after(qp605_s_5)

而且有效!

顺便说一句,根据 Stata 编程简介,这种方法比先 generate 一个全为零的变量然后 replace 循环,因为replace命令比generate慢,所以最好避免replace.

这是另一种方法。

* Example generated by -dataex-. For more info, type help dataex
clear
input float(var1 var2)
1 5
2 6
3 7
4 8
end

gen wanted = .

mata :

data = st_data(., "var*")

st_store(., "wanted", rowsum(data :>= 1 :& data :<= 5))

end

list

     +----------------------+
     | var1   var2   wanted |
     |----------------------|
  1. |    1      5        2 |
  2. |    2      6        1 |
  3. |    3      7        1 |
  4. |    4      8        1 |
     +----------------------+