2

想象一下,您必须在 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

2 回答 2

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

于 2011-10-06T19:17:39.420 回答
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'

}
于 2011-11-02T21:58:16.167 回答