How to fill in values ​​in a vector?

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!

+4
source share
3 answers

One option is to replace those 0with NA, and 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

, , replace,

zoo::na.locf(replace(x, x == 0, NA))
+7

:

k <- c(1,0,0,0,0,0,2,0,0,0,0,0,4,0,0,0)
k[which(k != 0)[cumsum(k != 0)]]

, cummax

k <- c(1,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0)
k[which(k != 0)[cumsum(k != 0)]]

:

  • "" , which(k != 0), x, x=c(1, 7, 13)

  • "" . ? k , , cumsum(k != 0), y y=c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3)

  • "" x: x[y], .. x 6 , 6 3 . z, z=c(1, 1, 1, 1, 1, 1, 7, 7, 7, 7, 7, 7, 13, 13, 13)

  • "" k, k[z], .. 6 , 7- 6 , 13- 3 .

+4

Add @ 李哲源 answer:

If you want to replace the leading NAs with the closest non-NA value and replace the remaining NAs with the latest non-NA value, the codes can be:

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

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


All Articles