Search code examples
rlubridate

How to compare each date within a vector of dates to another date


I have a vector of dates, and I want to find out which of those dates fall within a certain interval of dates. For example:

library(lubridate)

df$dates <- c(ymd("1999-1-1", "2000-1-1", "2001-1-1"))
comparison_interval <- interval(ymd("2000-12-25"), ymd("2005-1-1"))

I want to compare the vector to the stated interval to see which of the dates in that vector are within the interval. Ultimately I want a boolean vector that I can put in the data frame. So in the example above, I would want a vector of FALSE, FALSE, TRUE. I have tried using %within%

df$dates %within% comparison_interval

But it returns an error saying "Argument 1 is not a recognized date-time." What is the best way to do this?


Solution

  • You could do this as a boolean expression:

    dates <- c(ymd("1999-1-1", "2000-1-1", "2001-1-1"))
    results <- dates >= ymd("2000-12-25") & dates <= ymd("2005-1-1")
    

    This would give you a logical vector.