简体   繁体   English

如何避免R自动将日期转换为数字?

[英]How to avoid R converting dates to numeric automatically?

How to avoid R converting dates to numeric in a for loop?如何避免R在for循环中将日期转换为数字? This is related to this question that shows the same behavior for mapply disabling mapply automatically converting Dates to numeric这与此问题有关,该问题显示了 mapply 禁用 mapply 自动将日期转换为数字的相同行为

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 禁用 mapply 自动将日期转换为数字

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.我重新打开了这个问题,因为重复循环在日期时间对象上导致数字迭代器询问为什么R 循环将日期和日期时间对象转换为数字,这个问题询问如何避免这种行为。 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. for循环将序列强制转换为向量,除非它是向量、列表或其他一些东西。 date is not a vector, and there is no such thing as vector of dates. date不是向量,也没有日期向量这样的东西。 So you need as.list to protect it from coercion to vector:所以你需要as.list来保护它免受强制转换为向量:

for (d in as.list(date)) print(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM