我有这个数据示例:
W1$age <- c(3,2,4,1,1,3,4,NA,2,NA)
我想创建一个列:
1被0
2,3,4被1
其他一切都是NA
我有这段代码:
library(memisc)
W1$age2 = cases(
"0"= W1$age == 1,
"1" = W1$age == 2 | W1$age == 3 | W1$age == 4,
"NA" = W1$age != c("0", "1", "2", "3", "4")
)
它给了我这个错误(我用Google搜索但我没有找到它):
Error in if (any(done == 0) && any(done > 1)) msg("conditions are neither exhaustive nor mutually exclusive") else if (any(done == :
missing value where TRUE/FALSE needed
In addition: Warning message:
In W1$age != c("0", "1", "2", "3", "4") :
longer object length is not a multiple of shorter object length
我希望你能帮我解决一些问题, 非常感谢!
答案 0 :(得分:0)
使用base
,您可以:
x<- c(3,2,4,1,1,3,4,NA,2,NA)
x[x==1]<-0 #for x equal 1 convert to 0
x[(x==2|x==3|x==4)]<-1 #for x equal to 2,3, or 4 convert to 1
x[(!x %in% c(0:4))]<-NA #if x is not equal to 0 - 4 convert to NA