R:在三列上添加带条件检查的列?

时间:2011-07-02 14:52:29

标签: r conditional-statements

我的df1如下:

df1 <- data.frame(A=c("a","b","c","d","e"), B=c("f","g","t","g","u"), C=c("M","NA","NA","NA","M"), D=c("A","NA","NA","NA","NA"), E=c("NA","NA","NA","NA","G"), G=c(1:5))

  A B  C  D  E G
1 a f  M  A NA 1
2 b g NA NA NA 2
3 c t NA NA NA 3
4 d g NA NA NA 4
5 e u  M NA  G 5

我想根据C,D和E列中的读数添加列。如果所有都是NA,我想将X添加到列H.如果其中任何一个都不是NA,我想在列H中添加YES结果如下:

  A B  C  D  E G H
1 a f  M  A NA 1 YES
2 b g NA NA NA 2 X
3 c t NA NA NA 3 X
4 d g NA NA NA 4 X
5 e u  M NA  G 5 YES

专家可以教我如何用R来有效地做到吗?

2 个答案:

答案 0 :(得分:5)

transform(df1, H = ifelse(is.na(C) & is.na(D) & is.na(E), "X", "YES"))

请注意,仅当NA实际编码为NA而不是字符串"NA"时才有效。

有关这些功能的说明,请参阅?transform?ifelse。单&运算符逐项对向量操作数,并对每对进行布尔运算,返回逻辑向量。

答案 1 :(得分:2)

对于某些种类,以下是使用apply的替代解决方案,不需要分别在每列上调用is.na

df1$H <- apply(df1[,3:5],1,function(x){if (!all(is.na(x))) "YES" else "X"})

与Daniel一样,需要注意将缺失值编码为NA而不是"NA"