在datetime对象上循环导致一个数字迭代器 [英] Looping over a datetime object results in a numeric iterator

查看:178
本文介绍了在datetime对象上循环导致一个数字迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要迭代 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 (中的之后的部分)是表达式评估向量(包括列表和表达式)或对象列表或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'".

所以你的日期向量被强制为 numeric ,因为 Date 对象不是严格的向量:

$ b

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 vector:

The same is true for POSIXct vectors:

is.vector(Sys.time())
# [1] FALSE
is.vector(as.numeric(Sys.time()))
# [1] TRUE

这篇关于在datetime对象上循环导致一个数字迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆