Reputation: 25
I am studying Stata programming with the book An Introduction to Stata Programming, Second Edition.
In chapter 4 there is code to generate
a variable that tests whether some other variables satisfy a logical condition, the code is like:
foreach v of varlist child1-child12{
local n_school "`n_school' + inrange(`v', 1, 5)"
}
gen n_school = `n_school'
When I change this code to suit my own data,
foreach v of varlist qp605_s_1-qp605_s_5 {
local n_med "`n_med' + inrange(`v', 1, 5)"
}
gen n_med = `n_med'
where qp605_s_1
's values range from 1 to 17, then 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);
Any ideas what is wrong with this code?
Upvotes: 0
Views: 187
Reputation: 25
I see where I was wrong
The local n_med
begins with +
, so I change it to:
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)
and it works!
BTW, according to An Introduction to Stata Programming, this method is faster than if you first generate
a variable which is all zero and then replace
it by a loop, because the replace
command is slower than generate
, so it is better to avoid replace
.
Upvotes: 1
Reputation: 37208
Here is another approach.
* 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 |
+----------------------+
Upvotes: 0