繁体   English   中英

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)
}

如何在metric参数中这样指定函数,以使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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM