0

我正在编写一个函数,我想在其中改变感兴趣的统计数据(平均值、中位数、标准差)。是否可以获取统计信息的名称并将其添加到列名中?这是我正在尝试的:

DRG_stats_function <- function(df, statistic){
  df %>%
    group_by(Code) %>%
    summarize(across(Payments, statistic)) %>%
    knitr::kable(col.names = c('Code', paste0(statistic, 'of Payments')))
}

我希望列的标题是“代码”和“支付方式”/“支付中位数”/“支付标准偏差”。

我尝试过 str(statistic)、deparse(substitute())、as_label() 以及其他许多类似的方法。

4

1 回答 1

1

使用deparse+substitute应该可以。

library(dplyr)

DRG_stats_function <- function(df, statistic){

  column_name <- deparse(substitute(statistic))
  df %>%
    group_by(Code) %>%
    summarize(across(Payments, statistic)) %>%
    knitr::kable(col.names = c('Code', paste0(column_name, 'of Payments')))
}

DRG_stats_function(data, median)

across但是,如果您仅在一列上应用该函数 ( Payments) ,则不需要

DRG_stats_function <- function(df, statistic){
  column_name <- deparse(substitute(statistic))
  df %>%
    group_by(Code) %>%
    summarize(!!paste(column_name, 'of Payments') := statistic(Payments)) %>%
    knitr::kable()
}
于 2020-11-02T02:02:23.327 回答