Search code examples
rdateif-statementas.date

R: Extract data based on date, "if date lesser than"


I have a dataset with two values for each date like this:

    date        x   y
1   2013-05-01  1   2
2   2013-05-02  2   2
3   2013-05-03  3   2

date is in the format as.Date, using the package lubridate.

Now I want to have the mean of the two values, except for a certain time span, in which I want to use the values of x.

I tried the following:

mean=(x+y)/2

newdata=ifelse((data$date < 2013-10-01 | date$date > 2014-04-09), mean, x)

but if will just take the mean for all dates.

Is it possible to use greater/lesser than relationships for dates? Any suggestions on how to make this work?

Thanks in advance


Solution

  • It looks like you are not casting the comparison values as dates. Also the dates you used for comparison don't exclude any of the dates in the dataframe you provided so I'd expect the mean to be selected every time.

    date <- as.Date(c('2013-05-01', '2013-05-02', '2013-05-03'))
    x    <- c(1, 2, 3)
    y    <- c(2, 2, 2)
    mean <- (x + y)/2
    df   <- data.frame(date = date, x = x, y = y)
    newdata <- ifelse((df$date < as.Date('2013-05-02') | df$date > as.Date('2014-04-09')), mean, x)
    
    newdata
    

    I changed the dates in the condition to be more selective and I got 1.5 2.0 3.0. It selects the first value from mean and the others from x which agrees with the condition I used in the ifelse().