R如果具有NA值的函数则嵌套

时间:2014-08-14 13:53:08

标签: r if-statement nested na

我是新人并且自学成为R所以请耐心等待我。

我有一个带有1,0和NA值的变量A [因子类型变量]。我想基于variableA值创建一个变量B.如果VariableA为1,则变量B应为"String 1",如果变量A为0,"String 2“,如果变量A为<NA>,我希望将变量B保留为[{1}}变量已经有字符串]。

VarA    VarB
<NA>    
1   
0   
0   
0   
1   
1   
1   
0   
0   
<NA>    

到目前为止,我所尝试的并没有很好。以下是两个例子:

  if (df$VarA == 1){
    df$VarB <- "String1"
  } else if (df$VarA == 0){
      df$VarB <- "String2"
  } else{
    df$VarB <- df$VarB
  }

这给出了一个我无法发现的错误。

我尝试的第二件事是以下内容,它将所有VarB变为“String2”

ifelse(df$VarA == 1, df$VarB <- "StringA", df$VarB <- "String2")

任何帮助/建议/指导,说明为什么它没有得到高度赞赏。

1 个答案:

答案 0 :(得分:0)

我相信你正在寻找一个循环。您也可以使用一个功能。

#your data frame with NA, 1 and 0s
dd<-data.frame(VarA=c(NA,1,0,0,0,1,1,1,0,0,NA))
#a for loop to create the new vector in the data frame dd
for(i in 1:nrow(dd)){
#if there is an NA you will have an NA in the new vector
#here the i indicates the row we are using to get the information for the 
#new vector. It also indicates what loop we are on
  if(is.na(dd$VarA[i])){
    dd$VarB[i] <- dd$VarA[i]
#if there is a 1 in the old vector put a "String1" in the new vector
  }else if (dd$VarA[i]==1){
    dd$VarB[i] <- "String1"
#if there is a 0 in the old vector put a "String2" in the new vector
  }else if(dd$VarA[i]==0){
    dd$VarB[i] <- "String2"
#if the varible is not an NA, 1, or 0, tell me (print) that there is an error.
  }else{print("some thing is wrong")}
}