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

如何在R中指定行后插入计算对应列平均值的新行?

给R数据框插入组均值行的实现方案

原始数据框

首先定义你的原始数据框:

df <- structure(list(ACT = c(23.13958, 23.04186967, 24.20995687, 24.40250502, 
24.04483881, 23.30146732, 24.29608776, 23.39981921), DnaJ = c(22.03439246, 
21.88943566, 22.42216211, 23.16443426, 26.60619229, 27.85283015, 
23.44923267, 23.1289117), `EF-1` = c(22.68375722, 22.30853321, 
22.78175571, 23.60114283, 23.44663203, 24.71161093, 23.12476878, 
23.08036574)), row.names = c("Hairy root_1", "Hairy root_2", 
"Adventitious root_1", "Adventitious root_2", "Embryonic root_1", 
"Embryonic root_2", "Leaf_1", "Leaf_2"), class = "data.frame")

实现步骤(Base R)

直接用Base R代码完成需求,无需额外加载包:

# 1. 按每2行分组,计算每组各列的均值
mean_groups <- lapply(split(df, rep(1:4, each = 2)), colMeans)
mean_df <- do.call(rbind, mean_groups)

# 2. 设置均值行的行名(匹配对应样本类型)
rownames(mean_df) <- gsub("_\\d$", "_mean", rownames(df)[seq(2, 8, 2)])

# 3. 合并原始行与均值行,按顺序排列
new_df <- data.frame()
for (i in 1:4) {
  # 取出当前组的2行原始数据 + 对应均值行
  group_rows <- df[((i-1)*2 + 1):(i*2), ]
  new_df <- rbind(new_df, group_rows, mean_df[i, ])
}

结果展示

运行上述代码后,new_df的结构如下:

print(new_df)
#                     ACT      DnaJ     EF-1
# Hairy root_1    23.139580 22.034392 22.683757
# Hairy root_2    23.041870 21.889436 22.308533
# Hairy root_mean 23.090725 21.961914 22.496145
# Adventitious root_1 24.209957 22.422162 22.781756
# Adventitious root_2 24.402505 23.164434 23.601143
# Adventitious root_mean 24.306231 22.793298 23.191449
# Embryonic root_1 24.044839 26.606192 23.446632
# Embryonic root_2 23.301467 27.852830 24.711611
# Embryonic root_mean 23.673153 27.229511 24.079122
# Leaf_1          24.296088 23.449233 23.124769
# Leaf_2          23.399819 23.128912 23.080366
# Leaf_mean       23.847953 23.289072 23.102567

补充说明

  • 代码通过split将数据按每2行分组,确保每个样本类型的重复数据被归为一组
  • 用colMeans计算每组的列均值,保证均值行与原始行的列对应
  • 循环合并时严格遵循「原始两行 + 均值行」的顺序,满足你在第2、4、6、8行后插入均值的要求

内容的提问来源于stack exchange,提问作者A.Mokhtari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:02:46