2016-04-25 12 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