为什么要遍历 Date
或 POSIXct
对象结果 numeric
?例如:
test = as.Date("2009-01-01")
print( class( test ) )
# [1] "Date"
for ( day in test )
{
print( class( day ) )
}
# [1] "numeric"
同样的事情发生在
POSIXct
:test = as.POSIXct("2009-01-01")
print( class( test ) )
# [1] "POSIXct" "POSIXt"
for ( day in test )
{
print( class( day ) )
}
# [1] "numeric"
最佳答案
?"for"
说 seq
( in
之后的部分)是“[A]n 表达式计算向量(包括列表和表达式)或对列表或'NULL'”。
所以你的 Date
vector 被强制到 numeric
因为 Date
对象不是严格的向量:
is.vector(Sys.Date())
# [1] FALSE
is.vector(as.numeric(Sys.Date()))
# [1] TRUE
POSIXct
也是如此向量:is.vector(Sys.time())
# [1] FALSE
is.vector(as.numeric(Sys.time()))
# [1] TRUE
关于r - 循环遍历 Date 或 POSIXct 对象会产生一个数字迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074344/