Pat
Pat

Reputation: 1339

Ifelse Condition in xts Object

This is a simple one but I dont get the the correct answer myself. I have an xts object with NAs and ones

require(xts)
set.seed(21)
A <- xts(c(NA,NA,NA,1,NA,NA,NA,NA,NA,NA), Sys.Date()-10:1)
colnames(A) <- c("A")

What I am searching for is the ifelse loop that puts a 0 in A exactly 5 days after the 1 occured:

> A
            A
2014-12-23 NA
2014-12-24 NA
2014-12-25 NA
2014-12-26  1
2014-12-27 NA
2014-12-28 NA
2014-12-29 NA
2014-12-30 NA
2014-12-31  0
2015-01-01 NA

If by chance there is also a 1 exactly 5 days after the first one (i.e. on 2014-12-31 = 1) then the 1 should be kept.

Upvotes: 0

Views: 848

Answers (1)

Stibu
Stibu

Reputation: 15947

The lubridate package has the function days which makes it easy to add a number of days to a given date. The following has worked for me

library(lubridate)
dates.with.1 <- index(A[A==1])
plus.5.days <- dates.with.1 + days(5)
A[index(A) %in% plus.5.days & (is.na(A) | A!=1)] <- 0

The indexing in the last line is somewhat complicated and there is probalby a better way to do this. I had to use index because indexing directly with dates can not be combined with boolean indexing. That is, the following does not work:

A[plus.5.days & (is.na(A) | A!=1)] <- 0

Upvotes: 3

Related Questions