indexing - recursive replacement in R -


i trying clean data , replace zeros values previous date. hoping following code works 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 of

1 2 4 5 5 5 6 7 

which hoping for. there nice way of doing without looping?

the operation called "last observation carried forward" , used fill data gaps. it's common operation time series , implemented in package 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 

Comments