I have a vector with many zeros.
v <- c(3,0,0,5,0,0,0,10,0,0,0,0)
I want to distribute the nonzero numbers forward and replace everything before a nonzero number with the 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?
You are looking for the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With