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

R语言按Date分组计算DIC均值 新增Depth为100的数据行

R 为数据框按分组规则新增行实现方案

核心规则回顾

  • 以Date列为分组键,相同Date值归为一组
  • 每组计算DIC列均值作为新行的DIC取值
  • 新行Date和所属分组一致,Depth固定为100,最终追加到原数据框

方法1:Base R 实现(无第三方依赖)

不需要额外安装包,直接运行即可:

# 加载示例数据
df<-structure(list(Date = c(18381L, 18381L, 18448L, 18448L, 18395L, 
                            18395L, 18402L, 18402L, 18409L), Depth = c(50L, 150L, 50L, 150L, 
                                                                       50L, 150L, 50L, 150L, 50L), DIC= c(2157L, 2150L, 2161L, 2154L,2144L, 2152L, 2123L, 2155L, 2137L)), class = "data.frame", row.names = c(NA,-9L))

# 按Date分组计算DIC均值,构造新行
new_rows <- aggregate(DIC ~ Date, data = df, FUN = mean)
new_rows$Depth <- 100
new_rows <- new_rows[, colnames(df)] # 对齐原数据列顺序

# 合并原数据与新行,按Date、Depth排序便于查看
final_df <- rbind(df, new_rows)
final_df <- final_df[order(final_df$Date, final_df$Depth), ]

运行后每个Date分组都会生成对应规则的新行,例如Date=18381分组的DIC均值为2153.5,对应新行记录为Date=18381, Depth=100, DIC=2153.5。如果需要DIC保持整数,可将均值计算部分改为FUN = function(x) round(mean(x))。

方法2:dplyr 实现(适合大数据量/tidyverse工作流)

如果日常使用tidyverse生态处理数据,可使用更简洁的链式语法:

library(dplyr)

final_df <- df %>%
  group_by(Date) %>%
  # 按规则生成每组新行
  summarise(DIC = mean(DIC), Depth = 100, .groups = "drop") %>%
  select(all_of(colnames(df))) %>% # 对齐列顺序
  bind_rows(df, .) %>% # 追加到原数据
  arrange(Date, Depth) # 排序

内容的提问来源于stack exchange,提问作者Grg Lulu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:06:48