循环遍历 Date 或 POSIXct 对象会产生一个数字迭代器 [英] Looping over a Date or POSIXct object results in a numeric iterator
本文介绍了循环遍历 Date 或 POSIXct 对象会产生一个数字迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么遍历 Date
或 POSIXct
对象会导致 numeric
?例如:
Why does iterating through a Date
or POSIXct
object result in numeric
? For example:
test = as.Date("2009-01-01")
print( class( test ) )
# [1] "Date"
for ( day in test )
{
print( class( day ) )
}
# [1] "numeric"
同样的事情发生在 POSIXct
上:
The same thing happens with 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'".
?"for"
says that seq
(the part after in
) is "[A]n expression evaluating to a vector (including a list and an expression) or to a pairlist or 'NULL'".
所以你的 Date
向量被强制为 numeric
因为 Date
对象不是严格的向量:
So your Date
vector is being coerced to numeric
because Date
objects aren't strictly vectors:
is.vector(Sys.Date())
# [1] FALSE
is.vector(as.numeric(Sys.Date()))
# [1] TRUE
对于 POSIXct
向量也是如此:
The same is true for POSIXct
vectors:
is.vector(Sys.time())
# [1] FALSE
is.vector(as.numeric(Sys.time()))
# [1] TRUE
这篇关于循环遍历 Date 或 POSIXct 对象会产生一个数字迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文