为什么下面的代码不是打印日期而是整数?
> for (t in seq(as.Date('20090101','%Y%m%d'),as.Date('20090105','%Y%m%d'),1 ))
+ {
+ print(t)
+ }
[1] 14245
[1] 14246
[1] 14247
[1] 14248
[1] 14249
正如@flodel 所建议的那样,for 循环保留类型而不是类:
h <- seq(as.Date('20090101','%Y%m%d'),as.Date('20090105','%Y%m%d'),1)
class(h)
[1] "Date"
> typeof(h)
[1] "double"
解决方法:
使用矢量化版本:
print(seq(as.Date('20090101','%Y%m%d'),as.Date('20090105','%Y%m%d'),1 ))
或遍历序列索引并检索日期[
:
for (i in seq_along(h)) {
dt <- h[i]
print(dt)
}
[1] "2009-01-01"
[1] "2009-01-02"
[1] "2009-01-03"
[1] "2009-01-04"
[1] "2009-01-05"