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

在R中生成指定分组前缀的平均新行,需代码可复用(适配dplyr)

使用dplyr实现高效数据清洗:添加分组均值汇总行

首先,重现你的示例数据框:

library(dplyr)

# 构造示例数据框
df <- tibble(
  ID = c("A", "B", "C", "D", "E", "F", "G"),
  V1 = 1:7,
  V2 = c(2,3,4,1,2,3,4),
  V3 = c(2,5,6,5,8,9,1),
  V4 = c(2,8,1,7,3,5,4),
  V5 = c(2,3,1,8,2,9,6),
  Group = c("B21", "B24", "A28", "A61", "A62", "C91", "D90"),
  Categorical_1 = rep("[Text]", 7),
  Categorical_2 = rep("[Text]", 7),
  Categorical_3 = rep("[Text]", 7)
)

接下来是可复用的实现代码,我们封装成通用函数以便后续重复使用:

# 定义函数:根据Group前缀生成均值汇总行
add_prefix_mean_row <- function(data, group_prefix, new_id, new_group) {
  data %>%
    filter(str_detect(Group, paste0("^", group_prefix))) %>%
    summarise(
      ID = new_id,
      across(V1:V5, mean),  # 批量计算数值列均值
      Group = new_group,
      across(starts_with("Categorical_"), ~ NA_character_)  # 分类列设为NA
    )
}

# 生成B2前缀的汇总行H
row_h <- add_prefix_mean_row(df, "B2", "H", "B22")
# 生成A6前缀的汇总行I
row_i <- add_prefix_mean_row(df, "A6", "I", "A64")

# 合并原数据与汇总行
df_updated <- bind_rows(df, row_h, row_i)

# 查看完整结果
print(df_updated, n = Inf)

代码说明:

  • add_prefix_mean_row函数:通过参数控制分组前缀、新行ID和Group名称,适配不同的汇总需求
  • str_detect(Group, paste0("^", group_prefix)):精准匹配以指定前缀开头的Group记录
  • across(V1:V5, mean):批量处理所有数值列,避免逐个列名重复编写
  • across(starts_with("Categorical_"), ~ NA_character_):统一将分类列设为NA,满足"分类变量无需复制到新行"的要求
  • bind_rows:保持原数据结构不变,直接追加新生成的汇总行

运行后,更新后的数据集会包含新行H(Group为B22,数值列是B2前缀行的均值)和新行I(Group为A64,数值列是A6前缀行的均值)。

内容的提问来源于stack exchange,提问作者flâneur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:50:41