将其转换为函数并泛化为任意数据、分组变量和值变量:
library(tidyverse)
means <- function(data, group, value) {
group = enquo(group)
value = enquo(value)
value_name = paste0("mean_", value)[2]
data %>% group_by(!!group) %>%
summarise(!!value_name := mean(!!value, na.rm=TRUE))
}
means(dat, Grade, Things)
Grade mean_Things
<dbl> <dbl>
1 2.00 90.0
2 3.00 77.5
如果我理解你的评论,下面的函数怎么样,它接受一个字符串作为value
参数:
means <- function(data, group, value) {
group = enquo(group)
value_name = paste0("mean_", value)
value = sym(value)
data %>% group_by(!!group) %>%
summarise(!!value_name := mean(!!value, na.rm=TRUE))
}
VarName = "Things"
means(dat, Grade, VarName)
Grade mean_Things
<dbl> <dbl>
1 2.00 90.0
2 3.00 77.5
由于该函数是通用的,因此您可以对任何数据框执行此操作。例如:
means(mtcars, cyl, "mpg")
cyl mean_mpg
<dbl> <dbl>
1 4.00 26.7
2 6.00 19.7
3 8.00 15.1
您可以进一步概括该功能。例如,此版本采用任意数量的分组列:
means <- function(data, value, ...) {
group = quos(...)
value_name = paste0("mean_", value)
value = sym(value)
data %>% group_by(!!!group) %>%
summarise(!!value_name := mean(!!value, na.rm=TRUE))
}
VarName = "Things"
means(dat, VarName, students, Grade)
students Grade mean_Things
<fct> <dbl> <dbl>
1 a 2.00 90.0
2 b 2.00 100
3 c 2.00 80.0
4 d 3.00 75.0
5 e 3.00 80.0