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

R语言实现多测量值时间点的三阶中心移动平均计算

问题需求

我的数据框中每个时间点包含2至4个测量值,需要计算移动平均值:每个时间点对应一个结果值,该值为当前时间点的所有测量值、前一个时间点的所有测量值以及后一个时间点的所有测量值的平均值。

原始数据与初始尝试

原始数据及排序代码如下:

cellcounts <-c(80, 188, 206, 162, 106,  90,  85, 109,  87,  94,  86, 196, 132, 135,  84, 122,  67,  88,  81, 121,   9,  93, 117, 91, 108, 103, 119, 100,  18,  98,  93, 119, 140, 160, 101,  82, 111, 103,  28,  72, 144,  85,   1)
time <-c(-2.7, -2.8, -2.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -2.7, -2.8, -2.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -3.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.7, -2.5, -2.6, -2.9, -3.0, -3.2, -3.3, -3.4, -3.5, -3.7, -3.8, -2.5, -2.6, -3.7, -3.8, -3.9)
df <- data.frame(cellcounts, time)
df <- df[order(df$time),]

初始尝试用zoo::rollapply直接滑动计算均值,但该方法是按行滑动,无法实现按时间分组后取相邻时间点的所有测量值求平均的需求。

解决方案

步骤1:提取唯一排序后的时间点

先从排序后的数据中提取所有唯一的时间点,确保时间序列顺序正确:

unique_times <- unique(df$time)

步骤2:计算每个时间点的窗口均值

遍历每个唯一时间点,匹配其前一个、当前、后一个时间点的所有测量值,计算平均值:

window_means <- sapply(seq_along(unique_times), function(i) {
  # 获取当前、前一个、后一个时间点,边界点仅取存在的时间
  current_time <- unique_times[i]
  prev_time <- if(i > 1) unique_times[i-1] else NA
  next_time <- if(i < length(unique_times)) unique_times[i+1] else NA
  
  # 筛选有效时间点并提取对应测量值
  target_times <- c(prev_time, current_time, next_time)
  target_times <- target_times[!is.na(target_times)]
  relevant_counts <- df$cellcounts[df$time %in% target_times]
  
  # 计算平均值
  mean(relevant_counts)
})

步骤3:生成结果数据框

将时间点与对应的窗口均值组合成最终结果:

result <- data.frame(
  time = unique_times,
  window_mean = window_means
)

print(result)

说明

  • 排序后的时间点保证了相邻时间点的顺序正确
  • 首尾两个时间点由于没有前一个/后一个时间点,会仅用两个时间点的所有测量值计算均值
  • 每个时间点的结果值,是其自身及相邻时间点所有测量值的整体平均值

内容的提问来源于stack exchange,提问作者Scott Neuro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:37:26