【问题标题】:Access to list elements in Stata访问Stata中的列表元素
【发布时间】:2011-10-05 19:24:24
【问题描述】:

假设您必须在 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')

【问题讨论】:

    标签: list foreach stata


    【解决方案1】:

    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

    【讨论】:

    【解决方案2】:

    对您的代码的其他一些建议和更正 - 首先,我将使用 -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'
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      相关资源
      最近更新 更多