且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用时间序列 R 中的先前值替换零

更新时间:2023-11-20 20:06:58

将来请让您的问题独立,包括库调用和 dput(x) 任何输入 的输出x.

In the future please make your questions self-contained including the library calls and dput(x) output of any input x.

我们假设这是一个动物园对象,如最后所示.我们将其称为 z,因为 df 表明它是一个数据框.

We assume this is a zoo object as shown at the end. We will call it z since df suggests that its a data frame.

library(zoo)

L <- rowSums(z != 0) > 0
z[] <- coredata(z)[which(L)[cumsum(L)],]

给予:

> z
           Quant1 Quant2
2013-01-18    400    200
2013-01-20    400    200
2013-01-21    400    200
2013-01-22    125    100
2013-01-23    120      0

注意:使用了这个输入:

z <- structure(c(400L, 400L, 400L, 125L, 120L, 200L, 200L, 200L, 100L, 
0L), .Dim = c(5L, 2L), .Dimnames = list(NULL, c("Quant1", "Quant2"
)), index = structure(c(15723, 15725, 15726, 15727, 15728), class = "Date"), 
class = "zoo")