7

Why does 'for' convert dates to numeric and what's the best way to loop through dates?

mnths <- c(as.Date("2016-02-01"),as.Date("2016-03-01"))

str(mnths[1])
Date[1:1], format: "2016-02-01"

for (m in mnths) {
  str(m)
}
num 16832
num 16861
Mist
  • 1,888
  • 1
  • 14
  • 21
  • It seems to drop the "Date" class, rather than coercing to numeric. But it's not documented, as far as I can see. Nice find. – Rich Scriven Mar 18 '16 at 01:09
  • 1
    perhaps slightly documented under `seq` argument.. try `as.pairlist(mnths)` or `as.vector(mnths)` – user2957945 Mar 18 '16 at 01:10
  • 1
    Try: `for(m in as.list(mnths)) str(m)` . r-devel is supposed to have extended `for` to work with any class having `[[` and `length` methods but I just tried it and it still has the same behavior here. – G. Grothendieck Mar 18 '16 at 01:17
  • 1
    As far as I can tell `factor` seems to be the only "underlying integer/numeric" class getting [special treatment](https://github.com/wch/r-source/blob/394c11cef89f23edb45353442008b2c5adceb6f6/src/main/eval.c#L1606-L1613). Another workaround would be to use something like `for (i in seq_along(mnths)) { mnths[i] }`. – nrussell Mar 18 '16 at 01:18
  • This (the current, numeric structure of your mnths) may be the best way to describe your dates, however, as you can specify the starting date (```base::as.Date defaults to origin = "1900-01-01"```) and not have to worry too much about class issues. (see ```?base::as.Date```) – Jessica Burnett Jan 12 '21 at 16:11

0 Answers0