3

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 ?

Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92
  • Please don't use `if_else` or `ifelse` on dates. Instead try `setDT(df1)[date_vector>= date_vector2, newcol := date_vector1]` – akrun Jun 01 '17 at 09:59

3 Answers3

1

We can use data.table to create a new column

library(data.table)
setDT(df1)[date_vector1>= date_vector2, newcol := date_vector1]
df1
#   date_vector1 date_vector2     newcol
#1:   2017-05-29   2017-05-13 2017-05-29  
#2:   2017-05-22   2017-05-26       <NA>
#3:   2017-05-26   2017-05-18 2017-05-26
#4:   2017-05-28   2017-05-14 2017-05-28
#5:   2017-05-25   2017-05-27       <NA>

If both these are vectors are not a variable in a data.frame/data.table, then do

i1 <- date_vector1>= date_vector2
newvector <- date_vector2
newvector[i1] <- date_vector1[i1]
newvector[!i1] <- NA
newvector
#[1] "2017-05-29" NA           "2017-05-26" "2017-05-28" NA    

It is better not to use ifelse on Date as dates are stored as integers it will coerce to integer class and we may have to convert it back to Date class again with as.Date(..., origin = '1970-01-01')

data

set.seed(24)
date_vector1 <- sample((Sys.Date() - 1:10), 5, replace = FALSE)
date_vector2 <- sample((Sys.Date() - 1:20), 5, replace = FALSE)
df1 <- data.frame(date_vector1, date_vector2)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    I finally went for `foo=date_vector1` and `foo[date_vector1>= date_vector2]=NA`, but your answer may be very valuable for other cases – Dan Chaltiel Jun 01 '17 at 10:31
1

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"
RobinGower
  • 928
  • 6
  • 14
0

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"
Mikko Marttila
  • 10,972
  • 18
  • 31