【发布时间】:2017-02-10 01:41:10
【问题描述】:
我正在尝试生成一个新变量,如下所示:
如果 testA 的值为 1,而 testB 的值为 1 ==> 将 testAB 编码为 1
如果 testA 的值为 1 而 testB 的值缺失或 0 ==> 将 testAB 编码为 1
如果 testA 的值缺失或为 0,而 testB 的值为 1 ==> 将 testAB 编码为 1
如果 testA 的值为 0 且 testB 的值为 0 ==> 将 testAB 编码为 0
如果缺少 testA 的值并且缺少 testB 的值 ==> 将 testAB 编码为 NA
我想出的代码如下所示不起作用。如果 testA 和 testB 为 1,似乎只生成 1,否则生成 NA。你有什么建议吗?谢谢!
df2$testAB<-ifelse((df1$testA == 1) | (df1$testB == 1),1,0),1, 0,NA))
【问题讨论】:
-
或许
as.numeric(as.logical(df1$testA) | as.logical(df1$testB))
标签: r if-statement recode