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
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.