替换 xts 对象中的值避免下标越界错误

Replacing values in xts object avoiding subscript out of bounds error

我有一个 xts 对象

library(xts)
A <- xts(c(1,NA,NA,NA,1,NA,NA,NA,NA,1,NA), Sys.Date()-11:1)
colnames(A) <- c("A")

我需要的是:每次观察到A中有一个1,那么

  1. 接下来的两天也应该包含一个 1(此处的下一天表示下一行)。
  2. 我们观察到 1 后的第三天应该是零。

所以结果应该是这样的

> A
              A
2014-12-28    1
2014-12-29    1
2014-12-30    1
2014-12-31    0
2015-01-01    1
2015-01-02    1
2015-01-03    1
2015-01-04    0
2015-01-05   NA
2015-01-06    1
2015-01-07    1

我试过的是

dates.with.1 <- which(A==1)
A[dates.with.1 + 1] <- 1
A[dates.with.1 + 2] <- 1
A[dates.with.1 + 3] <- 0

这给了我

Error in `[.xts`(x, i, which.i = TRUE) : subscript out of bounds

因为在 A 的末尾添加第二个 1 是不可能的。

如果 A 仅由 1NA 组成,如玩具示例中所示,则以下内容有效。

pmax(pmax(A,lag(A),lag(A,2),na.rm=TRUE), lag(A-A,3), na.rm=TRUE)
#            A
#2014-12-28  1
#2014-12-29  1
#2014-12-30  1
#2014-12-31  0
#2015-01-01  1
#2015-01-02  1
#2015-01-03  1
#2015-01-04  0
#2015-01-05 NA
#2015-01-06  1
#2015-01-07  1