Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distribute values in a vector

Tags:

function

r

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?

like image 556
Bogdan Avatar asked Sep 08 '17 02:09

Bogdan


1 Answers

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
like image 120
KU99 Avatar answered Nov 12 '22 13:11

KU99