I am working on an xts object that contains some 0s in one of the columns and I need to replace them with the last value different than 0 found in the sequence.
我正在处理一个xts对象,其中一个列中包含了一些0,我需要用与序列中找到的0不同的最后一个值替换它们。
For example, I am simplifying here using a regular R vector:
例如,我在这里用一个常规的R向量来简化:
v = c(1, 2, 3, 0, 0, 0)
I need to change all the 0s with the last value != 0 in the sequence, in this case 3. The resulting vector should be:
我需要用序列中的最后一个值!= 0来改变所有的0,在这种情况下是3。得到的向量应该是:
> v
[1] 1 2 3 3 3 3
How can I achieve this, possibly using transform() or another vector operation?
如何实现这一点,可能使用transform()或其他向量操作?
1 个解决方案
#1
4
Set the zeros to NA
and use na.locf
:
将0设为NA,并使用NA .locf:
x <- .xts(c(1, 2, 3, 0, 0, 0), 1:6)
x[x==0] <- NA
na.locf(x)
#1
4
Set the zeros to NA
and use na.locf
:
将0设为NA,并使用NA .locf:
x <- .xts(c(1, 2, 3, 0, 0, 0), 1:6)
x[x==0] <- NA
na.locf(x)