10

How to avoid R converting dates to numeric in a for loop? This is related to this question that shows the same behavior for mapply disabling mapply automatically converting Dates to numeric

date <- c('2008-02-20','2009-10-05')
date <- as.Date(date, format = '%Y-%m-%d')
date
[1] "2008-02-20" "2009-10-05"
for (i in date) print(i)
[1] 13929
[1] 14522

disabling mapply automatically converting Dates to numeric

Edit

I have reopened this question since the duplicate Looping over a datetime object results in a numeric iterator asks why R loops convert date and datetime objects to numeric, this question asks how to avoid that behavior. And the answer is to the point solving the problem, unlike the accepted and other answers in the duplicate, that correctly answer that other question.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
dleal
  • 2,244
  • 6
  • 27
  • 49
  • 1
    The `Date` class in Base R stores dates as number of days since the epoch, so what you are seeing is the real underlying data. Your question is really about presentation of that data. – Tim Biegeleisen Dec 13 '16 at 05:10
  • It's a hassle, but you can reconvert: `for (i in date) print(as.Date(i, origin = '1970-01-01'))` – alistaire Dec 13 '16 at 05:11

1 Answers1

14

The for loop coerces the sequence to vector, unless it is vector, list, or some other things. date is not a vector, and there is no such thing as vector of dates. So you need as.list to protect it from coercion to vector:

for (d in as.list(date)) print(d)
user31264
  • 6,557
  • 3
  • 26
  • 40