首页 > 解决方案 > 如何计算向量中的渐进平均值但在满足条件时重新启动?

问题描述

给出以下向量

x<-c(0,0,0,5.0,5.1,5.0,6.5,6.7,6.0,0,0,0,0,3.8,4.0,3.6)

我想要一个具有累积平均值的向量,例如

cumsum(x)/seq_along(x)

但每次两个后续值之间的差值大于 1.3 或小于 -1.3 时都会重新开始计算。我的目标是获得像

d<-c(0,0,0,5,5.05,5.03,6.5,6.6,6.37,0,0,0,0,3.8,3.9,3.8)

谢谢

标签: rmean

解决方案


您可以使用cumsum(abs(diff(x)) > 1.3))定义组,用于在每次差值大于 1.3 或小于 -1.3 时aggregate重新启动。cumsum(x)/seq_along(x)

unlist(aggregate(x, list(c(0, cumsum(abs(diff(x)) > 1.3))),
  function(x) cumsum(x)/seq_along(x))[,2])
# [1] 0.000000 0.000000 0.000000 5.000000 5.050000 5.033333 6.500000 6.600000
# [9] 6.400000 0.000000 0.000000 0.000000 0.000000 3.800000 3.900000 3.800000

推荐阅读