mutate_at 可以根据包装的函数名命名变量吗? (dplyr + rlang 问题)
Can mutate_at name a variable according to a wrapped function name? (dplyr + rlang question)
我想创建一个函数,用 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)
}
如何在度量参数中指定函数,使 mutate_at 使用函数的名称来重命名变量?
最好的莫里茨!
@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
我想创建一个函数,用 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)
}
如何在度量参数中指定函数,使 mutate_at 使用函数的名称来重命名变量?
最好的莫里茨!
@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