Reputation: 21
Imagine you have to run the following in Stata
tab var1 region if var1 > 4
tab var2 region if var2 > 32
tab var3 region if var3 > 7
and so on for many variables. Notice that the filter fed to if
depends on the variable.
I would like to do the same by iterating over a list of variables. Something like
thresholdList = "4 32 7 ..." /// don't know if this works
foreach myvar of var1 var2 var3 ... {
tab `myvar' region if `myvar' > thresholdList(`counter')
local counter = `counter' + 1
}
`
Clearly, the code here above does not work in Stata. I'm trying to understand how can I define a macro including a list of values and access each element of the list explicitly, i.e.
thresholdList(`counter')
Upvotes: 2
Views: 6362
Reputation: 651
A couple of other suggestions and corrections to your code - First, I'd use -tokenize- to iterate over your list of items, second use a local macro to store your thresholdList', and finally use "local counter
++counter'" instead of "local counter = counter+1" to iterate your counter, so:
clear
set obs 200
forval n = 1/3 {
g var`n' = ceil(runiform()*10)
}
g region = 1
loc thresholdList "4 32 7 " //here's your list
token `"`thresholdList'"'
**notice how tokenize stores these values:
di "`1'"
di "`2'"
**now you'll iterate i to reference the token locations:
loc i = 1
foreach myvar in var1 var2 var3 { //use 'of' not 'in'
tab `myvar' region if `myvar' > ``i''
loc i `++i' //iterates `i'
}
Upvotes: 0
Reputation: 385
Stata can do this. The syntax you want to use should be something like this:
local thresholdlist "4 32 7"
local varlist "var1 var2 var3"
local numitems = wordcount("`thresholdlist'")
forv i=1/`numitems' {
local thisthreshold : word `i' of `thresholdlist'
local thisvar : word `i' of `varlist'
di "variable: `thisvar', threshold: `thisthreshold'"
tab `thisvar' region if `thisvar' > `thisthreshold'
}
See: http://www.stata.com/support/faqs/lang/parallel.html
Upvotes: 5