using ifelse with Dates in R

Viewed 4078

I have a vector of dates and I want to set the date to NA if it is prior to another vector.

I tried ifelse(date_vector1>=date_vector2, date_vector1, NA), but the output is not a Date and applying as.Date() return an error.

I then tried dplyr::if_else(date_vector1>=date_vector2, date_vector1, NA_real_), but it returns the same error.

The error is this one :

Error in as.Date.numeric(value) : 'origin' must be supplied

How can I use the ifelse statement with dates ?

3 Answers

This because ifelse strips the class attribute. You can restore it with e.g.

date_vector3 <- ifelse(date_vector1>=date_vector2, date_vector1, NA)
class(date_vector3) <- "Date"

I normally go for replace() when one of the cases is a fixed value:

date1 <- Sys.Date() + c(-1, 0, 1)
date2 <- Sys.Date() + c(0, 0, 0)

replace(date1, which(date1 < date2), NA)
#> [1] NA           "2022-02-25" "2022-02-26"
Related