你可以使用以下方法来总结使用dplyr的数据框架中的多个列:
方法1:汇总所有列
#summarise mean of all columns
df %>%
group_by(group_var) %>%
summarise(across(everything(), mean, na.rm=TRUE))
方法2:汇总特定列
#summarise mean of col1 and col2 only
df %>%
group_by(group_var) %>%
summarise(across(c(col1, col2), mean, na.rm=TRUE))
方法3:汇总所有数字列
#summarise mean and standard deviation of all numeric columns
df %>%
group_by(group_var) %>%
summarise(across(where(is.numeric), list(mean=mean, sd=sd), na.rm=TRUE))
下面的例子展示了如何用下面的数据框架来实现每种方法:
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B'),
points=c(99, 90, 86, 88, 95, 90),
assists=c(33, 28, 31, 39, 34, 25),
rebounds=c(NA, 28, 24, 24, 28, 19))
#view data frame
df
team points assists rebounds
1 A 99 33 NA
2 A 90 28 28
3 A 86 31 24
4 B 88 39 24
5 B 95 34 28
6 B 90 25 19
例子1:汇总所有列
下面的代码显示了如何汇总所有列的平均值。
library(dplyr)
#summarise mean of all columns, grouped by team
df %>%
group_by(team) %>%
summarise(across(everything(), mean, na.rm=TRUE))
# A tibble: 2 x 4
team points assists rebounds
1 A 91.7 30.7 26
2 B 91 32.7 23.7
例子2: 总结特定列
下面的代码显示了如何总结只有点和篮板列的平均值:
library(dplyr)
#summarise mean of points and rebounds, grouped by team
df %>%
group_by(team) %>%
summarise(across(c(points, rebounds), mean, na.rm=TRUE))
# A tibble: 2 x 3
team points rebounds
1 A 91.7 26
2 B 91 23.7
例3: 总结所有数字列
下面的代码显示了如何汇总数据框中所有数字列的平均值和标准差:
library(dplyr)
#summarise mean and standard deviation of all numeric columns
df %>%
group_by(team) %>%
summarise(across(where(is.numeric), list(mean=mean, sd=sd), na.rm=TRUE))
# A tibble: 2 x 7
team points_mean points_sd assists_mean assists_sd rebounds_mean rebounds_sd
1 A 91.7 6.66 30.7 2.52 26 2.83
2 B 91 3.61 32.7 7.09 23.7 4.51
输出显示数据框架中所有数字变量的平均值和标准差。
注意,在这个例子中,我们用**list()**函数列出了我们想要计算的几个汇总统计量。
注意:在每个例子中,我们都利用了dplyr**across()**函数。你可以在这里找到这个函数的完整文档。
其他资源
下面的教程解释了如何使用dplyr执行其他常用函数: