gpt4 book ai didi

r - 多列dplyr过滤器不起作用

转载 作者:行者123 更新时间:2023-12-01 01:44:21 26 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

3年前关闭。




Improve this question



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。我这样做了:
exclude.code <- c(1, 3, 4)

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

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

编辑

我在评论中尝试了该方法,但仍然无效
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")得到你不想要的那些。
  • 然后申请 !在整个事情上“删除”它们。
  • 关于r - 多列dplyr过滤器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52852182/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com