R - DPLYR 通过多列过滤不起作用


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)

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

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

只需使用这个:

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

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

最新更新