【发布时间】:2020-07-27 20:41:06
【问题描述】:
我正在尝试使用 summarize_at() 和自定义函数来汇总多个列。我坚持的部分是函数ssmd() 旨在从group_by() 建立的组中获取一个值向量,并从该组之外获取另一个值向量。
在下面的示例中,x 应该是Month 的每组值的向量(根据当前组而变化),y 应该是Month == 5 的一组固定值。
# custom function
ssmd <- function(x, y){
(mean(x, na.rm = TRUE) - mean(y, na.rm = TRUE)) / sqrt(var(x, na.rm = TRUE) + var(y, na.rm = TRUE))
}
# dataset
d <- airquality
# this isn't working - trying to find the difference between the mean for each Month and the mean of Month 5, for columns Ozone, Solar.R, Wind, and Temp
d %>%
group_by(Month) %>%
summarize_at(vars(Ozone:Temp), funs(ssmd, x = ., y = .[Month == 5])) %>%
ungroup()
目前,这会产生以下错误:Error in mean(y, na.rm = TRUE) : argument "y" is missing, with no default。所以我认为我有一个语法错误,除了被困在如何从当前组之外访问值之外。
预期输出是一个数据框,每个月有一行,每个变量(Ozone、Solar.R、Wind 和 Temp)一列。
【问题讨论】: