【问题标题】:Exclude rows from data.frame depending on a subset of the data.frame根据 data.frame 的子集从 data.frame 中排除行
【发布时间】: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$f3df$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 来制作可重现的示例和基于此的预期输出

标签: r dataframe


【解决方案1】:

如果我们需要exclude 'f2'、'f3' 和 'f4' 值为 0 的行,只需执行 rowSums 以创建逻辑 vectorsubset 数据集

subset(df, rowSums(df[2:4]!=0) != 0)

更新

基于 OP 帖子中的更新

df[!rowSums(df[2:4] != "yes"),] 

【讨论】:

  • 我在这里使用了 0 和 1 用于说明目的,真正的 data.frame 将包含文本字符串,如 nanoyes 等。如果我要转换,此解决方案将有效相应的 0 和 1 中的文本字符串。
  • @T.Kiss 我将此解决方案仅用于说明目的。您可以将其扩展到真实数据。当有人发布带有可重现示例的问题时,我们希望它是真实数据的复制品。
  • 抱歉没有添加set.seed(),感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多