为什么迭代 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
向量被强制为 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/6434663/