如果您想应用功能以外的其他功能怎么办 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

因此,您可以看到试图 apply 该向量的功能无法正常工作。班级 obs.truncated

> class(obs.truncated)
[1] "POSIXt"  "POSIXlt"

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

有帮助吗?

解决方案

length() 在这种posixlt中,曾经报告为九个,但最近得到了纠正。

另外,当我这样做 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
> 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top