recursive replacement in R

◇◆丶佛笑我妖孽 提交于 2020-01-02 18:05:07

问题


I am trying to clean 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 of

1 2 4 5 5 5 6 7

Which I was hoping for. Is there a nice way of doing this without looping?


回答1:


The operation is called "Last Observation Carried Forward" and usually used to fill data gaps. It's a common operation for time series and thus 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



回答2:


You could use essentially your same logic except you'll want to apply it to the values vector that results from 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


来源:https://stackoverflow.com/questions/17591949/recursive-replacement-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!