满足条件时如何重新计算矢量BUT中的渐进平均值?

时间:2020-06-17 10:39:52

标签: r mean

给出以下向量

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)

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

也许您可以像下面这样尝试ave + findInterval

ave(x,findInterval(seq_along(x),which(abs(diff(x))>1.3)+1),FUN = function(v) cumsum(v)/seq_along(v))

给出

 [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