r - 循环遍历 Date 或 POSIXct 对象会产生一个数字迭代器

标签 r date for-loop attributes posixct

为什么要遍历 DatePOSIXct对象结果 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/

相关文章:

java - 制作从一周中的指定一天开始的日历

r - 在 `keep` 包中使用 `purrr` 函数的正确方法是什么

r - 扩展原始错误消息

R:计算 12 个月的累积返回

javascript:新日期,如何设置默认年份?

arrays - 将表示日期的 char 数组转换为自 1970 年以来的秒数

loops - For 和 While 循环 : differences, 问题及原因

javascript - HTML Javascript 在 for 循环中添加一个 var 作为输入值

c - 使 R 函数识别同一包中的 C 函数?

使用 new Date() 将 Javascript 字符串转换为日期