简体   繁体   English

在R中迭代POSIXlt

[英]Iterate over POSIXlt in R

Imagine I have an input vector of POSIXct objects: 想象一下,我有一个POSIXct对象的输入向量:

times.input <- c(
  as.POSIXct('2013-01-01 00:00:00', tz='GMT'),
  as.POSIXct('2013-01-01 00:00:01', tz='GMT')
)
class(times.input)
# [1] "POSIXct" "POSIXt" 

Some of the functions (like round or trunc ) transform POSIXct to POSIXlt : 一些函数(如roundtrunc )将POSIXct转换为POSIXlt

unique.dates <- unique(trunc(times.input, 'days')))
class(times.rounded)
# [1] "POSIXlt" "POSIXt"

Then, if we try to iterate or lapply this object, strange things happen: 然后,如果我们尝试迭代或lapply这个对象,会发生奇怪的事情:

lapply(X=unique.dates, FUN=print)
# [1] 0 0
# [1] 0 0
# [1] 4 4
# [1] 1 1
# [1] 0 0
# [1] 113 113
# [1] 2 2
# [1] 0 0
# [1] 0 0

It seems like POSIXlt is stored internally vertically as a list of vectors, and iteration goes over internal structure instead of iterating over each object. 似乎POSIXlt作为向量列表在内部垂直存储,迭代遍历内部结构而不是遍历每个对象。

I know that converting to POSIXct helps in this case, because POSIXct is stored as an integer internally, but I consider this solution to be ugly. 我知道在这种情况下转换为POSIXct帮助,因为POSIXct在内部存储为整数,但我认为这个解决方案很难看。

So my question is: given a POSIXlt[2] data input, how to perform for loop or lapply over POSIXct objects? 所以我的问题是:给定一个POSIXlt[2]数据输入,如何对POSIXct对象执行循环或lapply

It's happening cause lapply works on list and you're right about storing, after help("DateTimeClasses") : 它正在发生,因为lapply在列表上工作,你是正确的存储,在help("DateTimeClasses")之后help("DateTimeClasses")

Class "POSIXlt" is a named list of vectors (...) 类“POSIXlt”是一个命名的向量列表(...)

If you really need to work with POSIXlt I propose convert to list, eg: 如果你真的需要使用POSIXlt我建议转换为list,例如:

times.input.L <- split(times.input, seq_along(times.input))
lapply(times.input.L, print)
[1] "2013-01-01 01:00:00 CET"
[1] "2013-01-01 01:00:01 CET"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM