gpt4 book ai didi

R xts : transform all 0 values in a time series with the last found value different than 0

转载 作者:行者123 更新时间:2023-12-01 12:55:41 24 4
gpt4 key购买 nike

我正在处理一个 xts 对象,其中一列中包含一些 0,我需要将它们替换为在序列中找到的最后一个不同于 0 的值。

例如,我在这里使用常规 R 向量进行简化:

v = c(1, 2, 3, 0, 0, 0)

我需要用序列中的最后一个值 != 0 更改所有 0,在本例中为 3。生成的向量应为:

> v
[1] 1 2 3 3 3 3

我怎样才能做到这一点,可能使用 transform() 或其他矢量操作?

最佳答案

将零设置为 NA 并使用 na.locf:

x <- .xts(c(1, 2, 3, 0, 0, 0), 1:6)
x[x==0] <- NA
na.locf(x)

关于R xts : transform all 0 values in a time series with the last found value different than 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9945262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com