簡體   English   中英

在 R 中編寫函數:將統計信息的名稱(作為變量)粘貼為列名

[英]Writing functions in R: paste name of statistic (as a variable) as column name

我正在編寫一個函數,我想在其中改變感興趣的統計數據(平均值、中位數、標准差)。 是否可以采用統計信息的名稱並將其添加到列名稱中? 這是我正在嘗試的內容:

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() 以及許多其他類似的方法。

使用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)

但是,如果您僅在一列( Payments )上應用該函數,則不需要across

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM