本文介绍了R中的递归替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试清理一些数据,并希望用前一个日期的值替换零。我希望以下代码有效,但它没有
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]
返回
1 2 4 5 5 0 6 7
而不是
1 2 4 5 5 5 6 7
我所希望的。
有没有一种很好的方法可以在没有循环的情况下做到这一点?
Which I was hoping for.Is there a nice way of doing this without looping?
推荐答案
该操作被称为最后观察结转通常用于填补数据空白。这是时间序列的常见操作,因此在包动物园中实现:
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
这篇关于R中的递归替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!