You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中编写封装summarize分组统计逻辑的自定义函数

R 分组统计自定义函数封装实现

你给出的函数雏形已经可以直接使用,调用时直接传入统计函数对象即可运行,基础实现代码如下:

library(tidyverse)

summarize_function <- function(statistic) {
  mtcars %>% 
    group_by(cyl) %>%
    summarise(var = statistic(mpg, na.rm = TRUE))
}

# 调用测试
# 计算均值
summarize_function(mean)
# 计算最大值
summarize_function(max)
# 计算最小值
summarize_function(min)

如果需要更高的复用性,支持自定义数据集、分组列、待计算数值列,可以使用dplyr的整洁评估语法{{ }}处理变量参数,实现通用版本:

summarize_function <- function(data, group_col, calc_col, statistic) {
  data %>% 
    group_by({{ group_col }}) %>%
    summarise(var = statistic({{ calc_col }}, na.rm = TRUE))
}

# 调用示例:按cyl分组计算hp列的最大值
summarize_function(data = mtcars, group_col = cyl, calc_col = hp, statistic = max)

如果需要返回的统计列名自动关联所用的统计函数和计算列,可以增加列名动态生成逻辑:

summarize_function <- function(data, group_col, calc_col, statistic) {
  # 动态生成结果列名
  result_col_name <- paste0(
    deparse(substitute(statistic)), 
    "_", 
    deparse(substitute(calc_col))
  )
  data %>% 
    group_by({{ group_col }}) %>%
    summarise(!!result_col_name := statistic({{ calc_col }}, na.rm = TRUE))
}

# 调用后返回列名为mean_mpg,可读性更强
summarize_function(mtcars, cyl, mpg, mean)

内容的提问来源于stack exchange,提问作者Alvaro Morales

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:15:02