0

Here is some code illustrating a behavior I don't love:

library(tidyverse)

> df <- data.frame(
+   the_date=c(as.Date("2021-01-01"), as.Date("2021-01-02")),
+   keep=c(T, T))

> df %>% summarize(the_min=min(the_date))
     the_min
1 2021-01-01

> df %>% summarize(the_min=min(ifelse(keep, the_date, NA)))
  the_min
1   18628

> df %>% summarize(the_min=as.Date(min(the_date), origin="1970-01-01"))
     the_min
1 2021-01-01

In the third case, the minimum of the dates is returned as 18628, whereas I'd like it to be a Date that is 2021-01-01. As shown, I can add back the as.Date with an origin of 1970-01-01, but do I have to?

P.S. It's tidyverse 1.3.0.

P.P.S. This seems related to Date shows up as number.

dfrankow
  • 20,191
  • 41
  • 152
  • 214
  • This should cover what you want: https://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects , e.g.: `dplyr::if_else(1 > 0:1, Sys.Date(), as.Date(NA))` should work how you want it to. – thelatemail Jun 23 '22 at 21:22
  • Ah! If you submit `as.Date(NA)` as an answer, I'll accept it. Or, we could mark this a dup. – dfrankow Jun 23 '22 at 21:31

1 Answers1

0

If you use case_when steady of ifelse it will work:

df %>% summarize(the_min = min(case_when(keep == TRUE ~ the_date)))

The case_when function works with the format: case_when("condition" ~ "result", "condition" ~ result) If the line does not meet any of the previous conditions, NA is returned.