2

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.

dfrankow
  • 20,191
  • 41
  • 152
  • 214

1 Answers1

4

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"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I accepted this answer, but .. do you know why the range with ":" converts to numeric? – dfrankow Jul 15 '22 at 17:38
  • @dfrankow if you check `?":"`, -`Non-numeric arguments are coerced internally (hence without dispatching methods) to numeric`, though it says `from:to is equivalent to seq(from, to), and generates a sequence from from to to in steps of 1 or -1.` it would not dispatch the correct 'Date' method – akrun Jul 15 '22 at 17:41