Distribute values ​​in vector

I have a vector with many zeros.

v <-(3,0,0,5,0,0,0,10,0,0,0,0)

I want to distribute nonzero numbers forward and replace everything up to a nonzero number with an average.

For example, (3,0,0) should be replaced by (1,1,1).

(3 + 0 + 0) / 3 = 1

v should become

(1,1,1,1.25,1.25,1.25,1.25,2,2,2,2,2)

Is there a function that can do this?

Thank.

+4
source share
1 answer

you are looking for a function ave

   ave(v,cumsum(v))
  [1] 1.00 1.00 1.00 1.25 1.25 1.25 1.25 2.00 2.00 2.00 2.00 2.00
+14
source

Source: https://habr.com/ru/post/1685272/


All Articles