POSIXct 和 sapply 的向量
如果您想将 format
以外的函数应用于 POSIXct 对象列表,该怎么办?例如,假设我想获取一个时间向量,将这些时间截断为小时,并对每个时间应用任意函数。
> obs.times=as.POSIXct(c('2010-01-02 12:37:45','2010-01-02 08:45:45','2010-01-09 14:45:53'))
> obs.truncated=trunc(obs.times, units="hours")
> obs.truncated
[1] "2010-01-02 12:00:00 EST" "2010-01-02 08:00:00 EST"
[3] "2010-01-09 14:00:00 EST"
现在,我预计 obs.truncated 的长度为 3,但是
> length(obs.truncated)
[1] 9
您可以看到,尝试将函数应用于此向量是行不通的。 obs.truncated 类是
> class(obs.truncated)
[1] "POSIXt" "POSIXlt"
知道这里发生了什么吗? apply
和 length
似乎将向量的第一个元素作为自己的列表。
What if you want to apply a function other than format
to a list of POSIXct objects? For instance, say I want to take a vector of times, truncate those times to the hour, and apply an arbitrary function to each one of those times.
> obs.times=as.POSIXct(c('2010-01-02 12:37:45','2010-01-02 08:45:45','2010-01-09 14:45:53'))
> obs.truncated=trunc(obs.times, units="hours")
> obs.truncated
[1] "2010-01-02 12:00:00 EST" "2010-01-02 08:00:00 EST"
[3] "2010-01-09 14:00:00 EST"
Now, I would expect the length of obs.truncated
to be 3 but
> length(obs.truncated)
[1] 9
So you can see that trying to apply
a function to this vector is not going to work. The class of obs.truncated
is
> class(obs.truncated)
[1] "POSIXt" "POSIXlt"
Any idea what is going on here? apply
and length
appear to be taking the first element of the vector as its own list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种 POSIXlt 的
length()
过去被报告为 9,但最近得到了更正。另外,当我执行 trunc(obs.times) 时,会发生错误的事情 - trunc() 只对三个元素的字符串执行一次。你确实需要
apply()
等。,这里是使用
sapply()
进行组件级重置的示例:因此
The
length()
of such a POSIXlt used to be reported as nine, but that got recently corrected.Also, when I do
trunc(obs.times)
the wrong thing happens --trunc()
operates only once on a string of three elements. you do needapply()
et al.So here is an example of using
sapply()
with component-wise resetting:Whereas