2016-04-25 64 views
0

我有这种数据例如:例使用误差(memisc)

W1$age <- c(3,2,4,1,1,3,4,NA,2,NA)

我想创建其中柱:

  • 1由0

  • 取代2,3,4被1取代

  • everything e LSE是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)&&任何(做> 1))MSG( “条件既不详尽也不相互排斥”)else if(any(done ==: missing value where TRUE/FALSE needed' – MSS

回答

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 
+0

It works @ User7598!'W1 $ age [W1 $ age ==“1”] < - 0 W1 $ age [(W1 $ age ==“2”| W1 $ age ==“3”| W1 $ age ==“4”)] < - 1'非常感谢! – MSS

+0

是的,这将起作用。 ..我添加了最后一行,以防你的向量中的值超出0 - 4,如果你不这样做,那么你所做的将会起作用。 – User7598