Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fill in values in a vector?

Tags:

r

vector

I have vectors in R containing a lot of 0's, and a few non-zero numbers.Each vector starts with a non-zero number.

For example <1,0,0,0,0,0,2,0,0,0,0,0,4,0,0,0>

I would like to set all of the zeros equal to the most recent non-zero number.

I.e. this vector would become <1,1,1,1,1,1,2,2,2,2,2,2,4,4,4,4>

I need to do this for a about 100 vectors containing around 6 million entries each. Currently I am 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?

Thanks!

like image 813
Kendall Reid Avatar asked Dec 14 '22 01:12

Kendall Reid


1 Answers

One option, would be to replace those 0 with NA, then use zoo::na.locf:

x <- c(1,0,0,0,0,0,2,0,0,0,0,0,4,0,0,0)
x[x == 0] <- NA
zoo::na.locf(x)  ## you possibly need: `install.packages("zoo")`
# [1] 1 1 1 1 1 1 2 2 2 2 2 2 4 4 4 4

Thanks to Richard for showing me how to use replace,

zoo::na.locf(replace(x, x == 0, NA))
like image 68
Zheyuan Li Avatar answered Jan 03 '23 14:01

Zheyuan Li