按组(group_by(id)
),我试图根据types
的选择求和一个变量。但是,这些types
有一个优先顺序。例:
library(tidyverse)
df <- data.frame(id = c(rep(1, 6), 2, 2, 2, rep(3, 4), 4, 5),
types = c("1a", "1a", "2a", "3b", "4c", "7d",
"4c", "7d", "7d","4c", "5d", "6d", "6d","5d","7d"),
x = c(10, 15, 20, 15, 30, 40,
10, 10, 15, 10, 10, 10, 10, 10, 10),
y = c(1:15),
z = c(1:15)
)
df
# id types x y z
# 1 1 1a 10 1 1
# 2 1 1a 15 2 2
# 3 1 2a 20 3 3
# 4 1 3b 15 4 4
# 5 1 4c 30 5 5
# 6 1 7d 40 6 6
# 7 2 4c 10 7 7
# 8 2 7d 10 8 8
# 9 2 7d 15 9 9
# 10 3 4c 10 10 10
# 11 3 5d 10 11 11
# 12 3 6d 10 12 12
# 13 3 6d 10 13 13
# 14 4 5d 10 14 14
# 15 5 7d 10 15 15
我想以此顺序基于
sum(x)
偏好设置来types
:preference_1st = c("1a", "2a", "3b")
preference_2nd = c("7d")
preference_3rd = c("4c", "5d", "6d")
因此,这意味着,如果
id
包含preference_1st
中的任何类型,我们将它们加总并忽略其他类型,如果preference_1st
中没有任何类型,则将所有preference_2nd
求和,而忽略其余的类型。最后,如果types
中只有preference_3rd
,则将它们加总。因此,对于id=1
,我们要忽略4c
和7d
类型。 (在此示例中,我还希望更直接地计算其他变量z
和y
)。所需的输出:
desired
id sumtest ymean zmean
1 1 60 3.5 3.5
2 2 25 8.0 8.0
3 3 40 11.5 11.5
4 4 10 14.0 14.0
5 5 10 15.0 15.0
我认为一个可能的选择是使用
mutate
和case_when
创建某种顺序变量,但是我认为if
语句应该有更好的选择?以下内容很接近,但不能正确区分首选项:df %>%
group_by(id) %>%
summarise(sumtest = if (any(types %in% preference_1st)) {
sum(x)
} else if (any(!types %in% preference_1st) & any(types %in% preference_2nd)) {
sum(x)
} else {
sum(x)
},
ymean = mean(y),
zmean = mean(z))
# id sumtest ymean zmean
# <dbl> <dbl> <dbl> <dbl>
# 1 1 130 3.5 3.5
# 2 2 35 8 8
# 3 3 40 11.5 11.5
# 4 4 10 14 14
# 5 5 10 15 15
也开放其他方法吗?有什么建议么?
谢谢
最佳答案
这是dplyr解决方案:
df %>%
group_by(id) %>%
mutate(ymean = mean(y), zmean = mean(z),
pref = 3 * types %in% preference_3rd +
2 * types %in% preference_2nd +
1 * types %in% preference_1st ) %>%
filter(pref == min(pref)) %>%
summarise(sumtest = sum(x), ymean = first(ymean), zmean = first(zmean))
#> # A tibble: 5 x 4
#> id sumtest ymean zmean
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 60 3.5 3.5
#> 2 2 25 8 8
#> 3 3 40 11.5 11.5
#> 4 4 10 14 14
#> 5 5 10 15 15
关于r - dplyr使用if语句根据订单条件进行汇总,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60672002/