2

I was wondering why R casts class Date into numeric when iterating over an array of Dates.

dates = as.Date(c("2017-01-01", "2017-01-02", "2017-01-03"))
for(i in 1:3) print(dates[i]) #Print Dates
[1] "2017-01-01"
[1] "2017-01-02"
[1] "2017-01-03"
for(d in dates) print(d) #Cast dates into numeric
[1] 17167
[1] 17168
[1] 17169
Victor Mayrink
  • 1,064
  • 1
  • 13
  • 24
  • 8
    The question is a FAQ, but the gist is that the attributes is dropped so the `Date` type becomes a simple integer. For that reason I tend to write my loops over the indices rather than vector elements as you did in example one. Right now I am forgetting what part the true culprit is but you just can't write the second loop over dates and retain the dates, sadly. – Dirk Eddelbuettel Oct 09 '17 at 17:30
  • 2
    @DirkEddelbuettel - seems like a good question - maybe post your comment as an answer? – dww Oct 09 '17 at 17:49
  • I had to look it up: In the `for` loop, the `dates` object is coerced to a vector and _e.g._ `as.vector(dates)` shows what happens here. – Dirk Eddelbuettel Oct 09 '17 at 18:06

0 Answers0