Recursive replacement in R

I am trying to clear some data and would like to replace zeros with values ​​from the previous date. I was hoping the following code works, but it doesn't

temp = c(1,2,4,5,0,0,6,7)
temp[which(temp==0)]=temp[which(temp==0)-1]

returns

1 2 4 5 5 0 6 7

instead

1 2 4 5 5 5 6 7

What I was hoping for. Is there a good way to do this without a loop?

+2
source share
2 answers

The operation is called "Last Observation Moved Forward" and is usually used to fill in data gaps. This is a common operation for time series and, thus, is implemented in a batch zoo:

temp = c(1,2,4,5,0,0,6,7)

temp[temp==0] <- NA

library(zoo)
na.locf(temp)
#[1] 1 2 4 5 5 5 6 7
+6
source

You can essentially use your own logic, except that you want to apply it to the value vector obtained by using rle

temp = c(1,2,4,5,0,0,6,0)

o <- rle(temp)
o$values[o$values == 0] <- o$values[which(o$values == 0) - 1]
inverse.rle(o)
#[1] 1 2 4 5 5 5 6 6
+2
source

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


All Articles