[R] converting character vector "hh:mm" to chron or strptime 24 clock time vectors

Sharpie chuck at sharpsteen.net
Wed Feb 17 04:45:06 CET 2010



Jim Lemon wrote:
> 
> On 02/16/2010 09:47 PM, Alex Anderson wrote:
>> ...
> This is the problem
>> 6 96.88 2008/04/24 24:00
>>
>> Error in `$<-.data.frame`(`*tmp*`, "time2", value = list(sec = c(0, 0, :
>> replacement has 9 rows, data has 10
> 
> Hi Alex,
> You have a problem with an invalid time. The line should read:
> 
> 6 96.88 2008/05/24 00:00
> 
> However, there is something else going on here that puzzles me. When I 
> tried this with your sample data:
> 
> tdata$datetime<-strptime(paste(tdata$date,tdata$time,sep="-"),"%Y/%m/%d-%H:%M")
> Error in `$<-.data.frame`(`*tmp*`, "datetime", value = list(sec = c(0,  :
>    replacement has 9 rows, data has 6
> 
> Yet:
> 
> datetime<-strptime(paste(tdata$date,tdata$time,sep="-"),
>   "%Y/%m/%d-%H:%M")
> datetime
> [1] "2008-04-24 02:00:00" "2008-04-24 04:00:00" "2008-04-24 06:00:00"
> [4] "2008-04-24 08:00:00" "2008-04-24 10:00:00" "2008-05-24 00:00:00"
> length(datetime)
> [1] 9
> 
> This is the first time I have encountered a discrepancy between "length" 
> and the printed extent of an object, and I can't work out what is going
> on.
> 
> Jim
> 

This is because you are working with a POSIXlt object which has 9 components
and therefore always has a length of 9.  That second part has always struck
me as an odd design decision-- but one which we will have to live with.  The
important detail is that each component of POSIXlt, such as "min", are the
length you would expect them to be.

I.E. if you have a POSIXlt object storing 15 timestamps:

  length( object )  = 9   <- not what you expect
  length( object$min ) = 15  <- what you expect

If it gets too confusing, just coerce your POSIXlt objects to POSIXct
objects which don't have issues with odd lengths.

Hope this helps!

-Charlie
-- 
View this message in context: http://n4.nabble.com/converting-character-vector-hh-mm-to-chron-or-strptime-24-clock-time-vectors-tp1557308p1558213.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list