【问题标题】:dplyr filter by multiple columns not working [closed]多列的dplyr过滤器不起作用[关闭]
【发布时间】:2019-03-21 23:22:16
【问题描述】:
df <- data.frame(code = rep(1:10, each = 3 * 3),
             type = rep(c("a", "b", "c"), each = 10 * 3),
             year = rep(1980:1982, each = 10 * 3),
             x = rnorm(90))

df <- df %>% dplyr::arrange(code, year, type)

我想删除type == acode 为 1、3 或 4 的 CODE 的所有行。我这样做了:

exclude.code <- c(1, 3, 4)

new.df <- df %>% dplyr::filter(!code %in% exclude.code & type != "a")

但这会删除所有不等于 a 的类型,即使我只想删除那些代码为 1、3 或 4 的 a。我做错了什么?

编辑

我尝试了评论中的方法,但仍然无效

head(df %>% dplyr::filter((!code %in% exclude.code) & type != "a"))

 code type year    x
  5    b 1981 -1.0564839
  5    b 1981  1.5385139
  5    b 1981  0.5709470
  5    b 1981  0.4728047
  5    b 1981 -0.3739578
  5    b 1981  0.6338270

【问题讨论】:

  • 对不起,这也不起作用
  • dplyr::filter(!(code %in% exclude.code) & (type != "a"))。 !的位置?
  • 抱歉不起作用。它可以在您的计算机上运行吗?
  • df %&gt;% dplyr::filter( !((code %in% exclude.code) &amp; (type == "a")) )

标签: r filter dplyr


【解决方案1】:

就用这个吧:

df %>% dplyr::filter( !((code %in% exclude.code) & (type == "a")) )
  • 这个 (code %in% exclude.code) &amp; (type == "a") 让你得到你不想要的。

  • 然后在整个事情上应用! 以“删除”它们。

【讨论】:

  • 现在可以使用了。谢谢
  • 有点难以理解。 Ronak 的评论很有帮助。
猜你喜欢
  • 2012-11-25
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 2021-04-23
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多