I have vectors in R containing many 0 and several nonzero numbers. Each vector starts with a nonzero number.
For example, <1,0,0,0,0,0,0,2,0,0,0,0,0,0,4,0,0,0>
I would like to set all zeros equal to the very last nonzero number.
those. this vector will become <1,1,1,1,1,1,2,2,2,2,2,2,4,4,4,4,4>
I need to do this for about 100 vectors containing about 6 million entries. I am currently using a for loop:
for(k in 1:length(vector){
if(vector[k] == 0){
vector[k] <- vector[k-1]
}
}
Is there a more efficient way to do this?
Thank!