1

I have an xts object

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

What I need is: every time we observe a 1 in A, then

  1. The next two days should contain also a 1 (the next day here means the next row).
  2. The third day after we observe a 1 should be a zero.

So the result should look like

> 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

What I have tried is

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

Which gives me

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

since adding the second 1 is not possible at the end of A.

Pat
  • 1,299
  • 4
  • 17
  • 40
  • Sure, `dates.with.1 + 2` gives 3,7 and 12. The last value is out the bounds of `A`, which is of length 11. –  Jan 08 '15 at 10:37
  • Yes I know. That is the Problem... Do you have any suggestions how to solve it? – Pat Jan 08 '15 at 10:43

1 Answers1

2

Following works if A consists only of 1s and NAs, as is given in the toy exaple.

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
Khashaa
  • 7,293
  • 2
  • 21
  • 37