在 Date 或 POSIXct 对象上循环会产生一个数字迭代器 [英] Looping over a Date or POSIXct object results in a numeric iterator

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

问题描述

为什么遍历 DatePOSIXct 对象会导致 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 向量也是如此:

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

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

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