你可以使用R中dplyr包中的over()函数来对多列进行转换。
有 无数种方法可以使用这个函数,但下面的方法说明了一些常见的用途。
方法1:对多列应用函数
#multiply values in col1 and col2 by 2
df %>%
mutate(across(c(col1, col2), function(x) x*2))
方法2:为多列计算一个汇总统计量
#calculate mean of col1 and col2
df %>%
summarise(across(c(col1, col2), mean, na.rm=TRUE))
方法3:为多列计算多个汇总统计量
#calculate mean and standard deviation for col1 and col2
df %>%
summarise(across(c(col1, col2), list(mean=mean, sd=sd), na.rm=TRUE))
下面的例子说明了如何用下面的数据框架来实现每种方法。
#create data frame
df <- data.frame(conf=c('East', 'East', 'East', 'West', 'West', 'West'),
points=c(22, 25, 29, 13, 22, 30),
rebounds=c(12, 10, 6, 6, 8, 11))
#view data frame
df
conf points rebounds
1 East 22 12
2 East 25 10
3 East 29 6
4 West 13 6
5 West 22 8
6 West 30 11
例1:对多列应用函数
下面的代码显示了如何使用across()函数将点和反弹列的值都乘以2。
library(dplyr)
#multiply values in points and rebounds columns by 2
df %>%
mutate(across(c(points, rebounds), function(x) x*2))
conf points rebounds
1 East 44 24
2 East 50 20
3 East 58 12
4 West 26 12
5 West 44 16
6 West 60 22
例2:为多列计算一个汇总统计值
下面的代码显示了如何使用across()函数来计算得分和篮板两列的平均值。
library(dplyr)
#calculate mean value of points an rebounds columns
df %>%
summarise(across(c(points, rebounds), mean, na.rm=TRUE))
points rebounds
1 23.5 8.833333
请注意,我们也可以使用is.numeric函数来自动计算数据框中所有数字列的汇总统计值。
library(dplyr)
#calculate mean value for every numeric column in data frame
df %>%
summarise(across(where(is.numeric), mean, na.rm=TRUE))
points rebounds
1 23.5 8.833333
例3:计算多个列的多个汇总统计量
下面的代码显示了如何使用across()函数来计算点和篮子两列的平均值和标准差。
library(dplyr)
#calculate mean and standard deviation for points and rebounds columns
df %>%
summarise(across(c(points, rebounds), list(mean=mean, sd=sd), na.rm=TRUE))
points_mean points_sd rebounds_mean rebounds_sd
1 23.5 6.156298 8.833333 2.562551
注:你可以在这里找到**across()**函数的完整文档。
其他资源
下面的教程解释了如何使用dplyr执行其他常用函数。
如何使用dplyr删除行
如何使用dplyr排列行
如何使用dplyr按多个条件过滤
The postHow to Use the across() Function in dplyr (3 examples)appeared first onStatology.