【问题标题】:Match values stored in local macros with those in a variable将存储在本地宏中的值与变量中的值匹配
【发布时间】:2019-06-05 16:16:47
【问题描述】:

在我的数据中,我有一个字符串变量ICD9CODX,如下所示:

|ICD9CODX|
|:-------|
|410     |
|411     |
|398     |
|196     |

我想在定义为 Stata 本地宏的某些代码集中搜索/匹配每个观察结果。因此,如果代码属于一个集合,则会创建一个标记该集合代码存在的变量并将其设置为值1,否则设置为0

我的本​​地宏示例如下:

local cond_1 410 411
local cond_2 398 402 428
...
local cond_17 196 197 198 199

预期结果:

|ICD9CODX|condition_1|condition_2|........|condition_17|
|:-------|----------:|----------:|--------|-----------:|
|410     |          1|          0|........|           0|
|411     |          1|          0|........|           0|        
|398     |          0|          1|........|           0|
|196     |          0|          0|........|           1|

我尝试使用下面的循环,但 0 进行了真正的更改:

forvalues i = 1/17 {
    generate condition_`i' = 0
    foreach dx in cond_`i' {
        replace condition_`i' = 1 if strtrim(ICD9CODX) == "`dx'"
    }
}

我的循环有什么问题?

【问题讨论】:

    标签: loops stata stata-macros


    【解决方案1】:

    跟踪你的循环。将i 设置为 1,然后

     cond_`i' 
    

    变成了

     cond_1 
    

    并且您的 replace 命令将您的变量与作为文字字符串的变量进行比较。这是合法的,但如果这不是变量的(修剪)值,则不会发生任何事情。其他 16 个案例(cond_2cond_17)也是如此。

    你应该写的完全不同:

    forvalues i = 1/17 {
        generate condition_`i' = 0
        foreach dx of local cond_`i' {
            replace condition_`i' = 1 if strtrim(ICD9CODX) == "`dx'"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-22
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 2022-01-14
      • 2021-02-01
      相关资源
      最近更新 更多