我正在尝试按组汇总变量列表。有些变量需要求和,有些需要取平均值。
我有这个:
Group Variable1 Variable2
1 10 2
1 12 6
2 6 7
2 4 9
我想要变量 1 的总和和变量 2 的平均值:
Group Variable1 Variable2
1 22 4
2 10 8
我一直在使用 dplyr 来获取组和:
sum <- (df %>%
group_by(Group) %>%
summarise_all(funs(sum)))
我正在尝试找到一种方法来选择对哪些列进行求和以及对汇总函数进行平均。
谢谢!
最佳答案
dplyr
的开发版本可以使用 across
选择性地将不同的函数应用于不同的变量集
library(dplyr)
df %>%
group_by(Group) %>%
summarise(across(Variable1:Variable2, sum), across(Variable3:Variable5, mean))
# A tibble: 2 x 6
# Group Variable1 Variable2 Variable3 Variable4 Variable5
# <int> <int> <int> <dbl> <dbl> <dbl>
#1 1 22 8 18.5 5 24
#2 2 10 16 11 7 20.5
df <- structure(list(Group = c(1L, 1L, 2L, 2L), Variable1 = c(10L,
12L, 6L, 4L), Variable2 = c(2L, 6L, 7L, 9L), Variable3 = c(24L,
13L, 10L, 12L), Variable4 = c(3L, 7L, 9L, 5L), Variable5 = c(26L,
22L, 23L, 18L)), class = "data.frame", row.names = c(NA, -4L))
https://stackoverflow.com/questions/60661367/
相关文章:
linux - 粘贴到终端/fish shell : [200~ and [201~ 时出现奇怪的字
javascript - 在 Promise 完成后让 React 重新渲染
oracle - PL/SQL RAISE_APPLICATION_ERROR 参数问题
regex - Ansible 列表变量和选择过滤器以忽略匹配项
azure - 如何在Azure Pipelines的步骤中使用变量作为条件?
javascript - Vue-Apexcharts 饼图总数不显示
flutter - 如何在 flutter, android studio 中不生成红色框,