让变量等于 if 语句中的多个值

Let a variable equal multiple values in an if-statement

我正在 Stata 中进行数据清理,如果一整套其他变量等于 16,我需要将一个变量重新编码为等于 1,或 7.

我可以使用以下代码执行此操作:

replace anyadl = 1 if diffdress==1 | diffdress==6 | diffdress==7 | ///
                      diffwalk==1  | diffwalk==6  | diffwalk==7  | ///
                      diffbath==1  | diffbath==6  | diffbath==7  | ///
                      diffeat==1   | diffeat==6   | diffeat==7   | ///
                      diffbed==1   | diffbed==6   | diffbed==7   | /// 
                      difftoi==1   | difftoi==6   | difftoi==7

但是这样打出来效率很低,而且很容易出错。

有更简单的方法吗?

例如,以下内容:

replace anyadl = 1 if diff* == (1 | 6 | 7)

你的幻想语法即使合法也不会做你想做的事,例如 1|6|7 将被评估为 1。也就是说,在 Stata 1 OR 6 OR 7 实际上是 true OR true OR true, so true, and thus 1, 给定规则非零作为输入为真,真为 1 作为输出。表达式是1|6|7是合法的;这是不是平等或不平等的通配符。

回过头来看,您的代码正在生成一个值为 1 或缺失的指标(有人说是虚拟)变量。在实践中,如果使用值 0 和 1 创建这样的变量(在某些情况下也会丢失),这样的变量会更有用。

generate anyad1 = 0 

foreach v in dress walk bath eat bed toi { 
    replace anyad1 = 1 if inlist(diff`v', 1, 6, 7) 
} 

是一种方法。通常,注意 inlist(foo, 1, 6, 7)inlist(1, foo, bar, bazz) 都是有用的结构。

阅读:

This paper on generating indicators

This one on useful functions

This one on inlist() and inrange()

FAQ on true and false in Stata