如何在R中的循环中显示实际日期 [英] How to display real dates in a loop in r
问题描述
当我循环遍历日期时,R打印出日期的数字编码.
When I iterate over dates in a loop, R prints out the numeric coding of the dates.
例如:
dates <- as.Date(c("1939-06-10", "1932-02-22", "1980-03-13", "1987-03-17",
"1988-04-14", "1979-08-28", "1992-07-16", "1989-12-11"), tryFormats = c("%Y-%m-%d"))
for(d in dates){
print(d)
}
输出如下:
[1] -11163
[1] -13828
[1] 3724
[1] 6284
[1] 6678
[1] 3526
[1] 8232
[1] 7284
如何获取R以打印出实际日期? 因此输出为:
How do I get R to print out the actual dates? So the output reads:
[1] "1939-06-10"
[1] "1932-02-22"
[1] "1980-03-13"
[1] "1987-03-17"
[1] "1988-04-14"
[1] "1979-08-28"
[1] "1992-07-16"
[1] "1989-12-11"
谢谢!
推荐答案
在R的for
循环中将dates
用作seq
时,它将丢失其属性.
When you use dates
as seq
in a for
loop in R, it loses its attributes.
您可以使用as.vector
剥离属性并自己查看(或dput
看到完整对象的内幕):
You can use as.vector
to strip attributes and see for yourself (or dput
to see under the hood on the full object):
as.vector(dates)
# [1] -11163 -13828 3724 6284 6678 3526 8232 7284
dput(dates)
# structure(c(-11163, -13828, 3724, 6284, 6678, 3526, 8232, 7284), class = "Date")
在R中,Date
对象只是具有class
Date
(class
是属性)的numeric
向量.
In R, Date
objects are just numeric
vectors with class
Date
(class
is an attribute).
因此,您会看到数字(FWIW,这些数字自1970-01-01
起算为天).
Hence you're seeing numbers (FWIW, these numbers count days since 1970-01-01
).
要恢复Date
属性,可以使用.Date
函数:
To restore the Date
attribute, you can use the .Date
function:
for (d in dates) print(.Date(d))
# [1] "1939-06-10"
# [1] "1932-02-22"
# [1] "1980-03-13"
# [1] "1987-03-17"
# [1] "1988-04-14"
# [1] "1979-08-28"
# [1] "1992-07-16"
# [1] "1989-12-11"
这等效于as.Date(d, origin = '1970-01-01')
,这是as.Date
的numeric
方法.
This is equivalent to as.Date(d, origin = '1970-01-01')
, the numeric
method for as.Date
.
有趣的是,*apply
函数不会去除属性:
Funnily enough, *apply
functions don't strip attributes:
invisible(lapply(dates, print))
# [1] "1939-06-10"
# [1] "1932-02-22"
# [1] "1980-03-13"
# [1] "1987-03-17"
# [1] "1988-04-14"
# [1] "1979-08-28"
# [1] "1992-07-16"
# [1] "1989-12-11"
这篇关于如何在R中的循环中显示实际日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!