Get Date objects back from min(dates):max(dates) in R?

Viewed 33

Some R code:

> dates <- as.Date(c('2020-01-01', '2020-01-02'))
> min(dates)
[1] "2020-01-01"
> max(dates)
[1] "2020-01-02"

> min(dates):max(dates)
[1] 18262 18263
> as.Date(min(dates):max(dates))
Error in as.Date.numeric(min(dates):max(dates)) : 
  'origin' must be supplied
> as.Date(min(dates):max(dates), origin="1970-01-01")
[1] "2020-01-01" "2020-01-02"

This shows that min and max are working as expected, but when I put them in a range, the dates turn into integers. How do I prevent that?

I can just use the "origin", but it seems like a hack.

1 Answers

Instead of using : and then reconverting the coerced numeric storage to Date class, use the seq which already have a method for Date class

seq(min(some_dates), max(some_dates), by = "1 day")
[1] "2020-01-01" "2020-01-02"
Related