2011-10-05 83 views
2

想象一下,你必须运行在Stata访问列表元素在Stata

以下
tab var1 region if var1 > 4 

tab var2 region if var2 > 32 

tab var3 region if var3 > 7 

等了很多变数。请注意,输入到if的过滤器取决于变量。

我想通过遍历变量列表来做同样的事情。像

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 
} 

`

东西显然,这里的代码上面并没有在Stata工作。我想了解我如何定义,包括值列表的宏和访问列表中明确的每一个元素,即

thresholdList(`counter') 

回答

4

塔塔能做到这一点。您要使用的语法应该是这样的:

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' 

} 

参见:http://www.stata.com/support/faqs/lang/parallel.html

+0

+1这将是有益的,但是,明确说明这些命令:“forvalues”,“display”等。 – StasK

+0

我从以下文章中学到了很多关于'forvalues'和'foreach':http://www.stata-journal.com/article.html?article=pr0005 – 2011-10-08 16:39:27

0

一对夫妇的其他建议和修正你的代码 - 首先,我会使用-tokenize-遍历您项目列表,第二个使用本地宏来存储您的thresholdList', and finally use "local counter ++反'”,而不是‘本地计数器=计数+ 1’进行迭代贵方,所以:

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' 

}