문제

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.

도움이 되었습니까?

해결책

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
> 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top