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 needapply()et al.So here is an example of using
sapply()with component-wise resetting:Whereas