POSIXct 和 sapply 的向量

发布于 2024-09-08 06:23:42 字数 682 浏览 2 评论 0原文

如果您想将 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"

知道这里发生了什么吗? applylength 似乎将向量的第一个元素作为自己的列表。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好菇凉咱不稀罕他 2024-09-15 06:23:42

这种 POSIXlt 的 length() 过去被报告为 9,但最近得到了更正。

另外,当我执行 trunc(obs.times) 时,会发生错误的事情 - trunc() 只对三个元素的字符串执行一次。你确实需要 apply() 等。

,这里是使用 sapply() 进行组件级重置的示例:

> sapply(obs.times, function(.) {
+ p <- as.POSIXlt(.); 
+ p$min <- p$sec <- 0; 
+ format(p) })
[1] "2010-01-02 12:00:00" "2010-01-02 08:00:00" "2010-01-09 14:00:00"
> 

因此

> trunc(obs.times, units="hours")
[1] "2010-01-02 12:00:00 CST" "2010-01-02 08:00:00 CST"
[3] "2010-01-09 14:00:00 CST"
> class(trunc(obs.times, units="hours"))
[1] "POSIXt"  "POSIXlt"
> length(trunc(obs.times, units="hours"))
[1] 1
> 

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 need apply() et al.

So here is an example of using sapply() with component-wise resetting:

> sapply(obs.times, function(.) {
+ p <- as.POSIXlt(.); 
+ p$min <- p$sec <- 0; 
+ format(p) })
[1] "2010-01-02 12:00:00" "2010-01-02 08:00:00" "2010-01-09 14:00:00"
> 

Whereas

> trunc(obs.times, units="hours")
[1] "2010-01-02 12:00:00 CST" "2010-01-02 08:00:00 CST"
[3] "2010-01-09 14:00:00 CST"
> class(trunc(obs.times, units="hours"))
[1] "POSIXt"  "POSIXlt"
> length(trunc(obs.times, units="hours"))
[1] 1
> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文