vector of POSIXct and sapply

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.

Answers


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
> 

Need Your Help

PHP crypt() function in .Net?

php .net asp.net security encryption

I'm rewriting a PHP web site in ASP.NET MVC. I'd like to maintain the same user base but the passwords are hashed using the PHP crypt() function. I need the same function in .Net so that I can hash a

Jersey client file upload exception: NoClassDefFoundError: org/glassfish/jersey/message/internal/HeadersFactory

java rest file-upload jersey

im trying to create a jersey client to upload files. I`ve searched the i-net but i cant find a proper solution for my exception.