访问Stata中的列表元素

时间:2011-10-05 19:24:25

标签: list foreach 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')

2 个答案:

答案 0 :(得分:4)

Stata可以做到这一点。您要使用的语法应该是这样的:

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

答案 1 :(得分:0)

对您的代码提出其他一些建议和更正 - 首先,我使用-tokenize-迭代您的项目列表,然后使用本地宏来存储您的thresholdList', and finally use "local counter ++ counter'“ “local counter = 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'

}