2012-12-07 73 views
2

爲什麼下面的代碼不是打印日期而是整數?R for for循環與類型轉換

> 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 

回答

3

正如@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" 
+0

有關問題的「爲什麼」的一部分的任何想法? – flodel

+0

誠實號可能是因爲班級日期的內部表示爲數字。 – agstudy

+2

找到了答案[這裏](https://stat.ethz.ch/pipermail/r-help/2008-December/182520.html)。 '爲'保留的類型,而不是班級。它還建議循環遍歷序列中的索引作爲解決方法。 – flodel