How to calcualte the progressive mean in a vector BUT restarting when a condition is met?

Viewed 38

giving the following vector

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)

I would like to have a vector with the cumulative mean, like

cumsum(x)/seq_along(x)

but restarting the computation each time that the difference between two subsequent values is grater than 1.3 or less than -1.3. My aim is to obtain a vector like

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)

Thanks

2 Answers

You can use cumsum(abs(diff(x)) > 1.3)) to define groups, which are used in aggregate to restart cumsum(x)/seq_along(x) each time when the difference is grater than 1.3 or less than -1.3.

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

Maybe you can try ave + findInterval like below

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

which gives

 [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
Related