gpt4 book ai didi

r - 使用 R 中的 dplyr 删除以其他行的值为条件的行

转载 作者:行者123 更新时间:2023-12-05 01:32:59 25 4
gpt4 key购买 nike

使用下面提供的示例数据:对于每个机构类型(“a”和“b”)我想删除 fac == “no” 的行,如果存在 fac == “yes” 的行年。然后我想按年对这些值求和。但是,我无法弄清楚如何删除正确的“否”行。以下是我根据给出的答案所做的一些尝试 here .

set.seed(123)
ext <- tibble(
institution = c(rep("a", 7), rep("b", 7)),
year = rep(c("2005", "2005", "2006", "2007", "2008", "2009", "2009"), 2),
fac = rep(c("yes", "no", "no", "no", "no", "yes", "no"), 2),
value = sample(1:100, 14, replace=T)
)

ext %>%
group_by(institution, year) %>%
filter(if (fac == "yes") fac != "no")

ext %>%
group_by(institution, year) %>%
case_when(fac == "yes" ~ filter(., fac != "no"))

ext %>%
group_by(institution, year) %>%
{if (fac == "yes") filter(., fac != "no")}

最佳答案

另一种方式是:

library(dplyr)
ext %>%
group_by(institution, year) %>%
filter(fac == 'yes' | n() < 2)

# institution year fac value
# 1 a 2005 yes 31
# 2 a 2006 no 51
# 3 a 2007 no 14
# 4 a 2008 no 67
# 5 a 2009 yes 42
# 6 b 2005 yes 43
# 7 b 2006 no 25
# 8 b 2007 no 90
# 9 b 2008 no 91
# 10 b 2009 yes 69

如果您想要按年计算的总金额,请添加这两行,这将产生以下输出:

group_by(year) %>%
summarise(value=sum(value))

# year value
# <chr> <int>
# 1 2005 74
# 2 2006 76
# 3 2007 104
# 4 2008 158
# 5 2009 111

关于r - 使用 R 中的 dplyr 删除以其他行的值为条件的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64957583/

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