我想创建一个函数,该函数用metric参数指定的特定指标来突变...中指定的所有变量。我在函数中使用mutate_at,并希望它使用“ var.functionname”重命名该变量。功能如下:
seasonAggregator <- function(.data, ..., metric = "sum") {
# all variables in ... will be accumulated
metric <- sym(metric)
name <- ensym(metric)
print(paste0("Metric for accumulation was: ", metric))
.data <- .data %>% mutate_at(vars(...), .funs = list(!!name := metric)) # HERE IS THE ISSUE
return(.data)
}
如何在metric参数中这样指定函数,以使mutate_at使用函数名称来重命名变量?
最佳莫里兹!
答案 0 :(得分:0)
@Moody_Mudskipper是正确的。您要使用支持准引号的rlang::list2()
。另外,由于要通过summarize_at
进行累积,因此您可能想要mutate_at
,而不是sum
。
seasonAggregator <- function(.data, ..., metric = "sum") {
## all variables in ... will be accumulated
print(paste0("Metric for accumulation was: ", metric))
.data <- .data %>%
summarize_at(vars(...), .funs = rlang::list2(!!metric := sym(metric)))
return(.data)
}
seasonAggregator( mtcars, mpg, cyl )
# [1] "Metric for accumulation was: sum"
# mpg_sum cyl_sum
# 1 642.9 198
seasonAggregator( mtcars, mpg, cyl, metric="mean" )
# [1] "Metric for accumulation was: mean"
# mpg_mean cyl_mean
# 1 20.09062 6.1875