【发布时间】:2017-07-06 06:14:50
【问题描述】:
我有以下模拟的data.frame:
(请注意,我已经重写了大部分问题,反映了 akrun 对我最初问题的回答)
set.seed(22)
df <- data.frame(f1 = rep("a", 20), f2 = factor(sample(c("yes", "no", "maybe", "maybenot"), 20, replace = T)), f3 = factor(sample(c("yes", "no"), 20, replace = T)), f4 = factor(sample(c("yes", "no"), 20, replace = T)))
f1 f2 f3 f4
1 a maybe yes yes
2 a no yes yes
3 a yes no no
4 a maybe yes no
5 a maybe no yes
6 a maybenot no yes
...
我想排除所有不在df$f2中显示yes,并在df$f3或df$f4中显示no的行。如果我将这些值手动转换为 0 和 1(除 yesin df$f2 之外的所有值都为 0),我可以按照 akrun 的建议使用 rowSums。我目前的解决方案是引入一个名为df$exclude 的虚拟列,如下所示,然后在df$exclude 上引入subset:
df$exclude <- "no"
df[df$f2 != "yes" | df$f3 == "no" | df$f4 == "no",]$exclude <- "yes"
df <- subset(df, exclude == "no")
这不能更简洁地完成吗,例如没有事先对 f2、f3 和 f3 列进行转换,或者使用lapply(以某种方式与subset 结合,可能还有一个匿名函数)?
提前感谢您的回答。
【问题讨论】:
-
我不确定您的编辑是如何达到目的的。
-
您的描述和代码似乎有冲突。您是否需要
df[!rowSums(df[2:4] != "yes"),]最好使用set.seed来制作可重现的示例和基于此的预期输出