1

My data, DATA, has a variable, TIME, for which the values print out in this format: "11/14/2006 20:10". For TIME, its mode is numeric and its class is a factor.

I need to convert TIME to a proper date/time variable (DTIME) and add the new DTIME to DATA as date.time. I was told I may have to coerce the time values so that they follow the h:m:s format...Think character string manipulation. Below is my code:

 library("chron")

VAR=c(as.character(DATA$TIME))
DT<-t(as.data.frame(strsplit(VAR," ")))
DT[1:3,]
row.names(DT)<-NULL
DT[1:3,]
DTIME<-chron(dates=DT[,1],times=DT[,2],
        format=c("m/d/y","h:m"))

But once I run the last line of code, I get the following error message:

Error in convert.times(times., format = format[[2]]) : 
  format h:m may be incorrect
In addition: Warning message:
In is.na(out$s) : is.na() applied to non-(list or vector) of type 'NULL'

I don't understand what this means, much less how to fix it.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Mike L
  • 486
  • 5
  • 16
  • 33
  • there appears to be a bug in `chron:::parse.format` called by `chron:::convert.times` whereby the format 'h:m' is not parsed correctly, whereas (say) 'h:m:s' *is* parsed correctly. not sure where that would be reported but in the meantime using `as.chron` as suggested in one of the answers below seems a good workaround – mathematical.coffee Apr 26 '13 at 01:04
  • That would be a desirable feature but it is not a bug. Its documented in `?chron` that the times format must be a permutation of `h`, `m` and `s`. – G. Grothendieck Apr 26 '13 at 01:09

3 Answers3

4

Its not clear from the question exactly what you have -- in such cases its best to show the output of dput applied to your variable -- but assuming you can convert it to character format using as.character or format then its just a matter of using as.chron :

> library(chron)
> TIME <- "11/14/2006 20:10"
> as.chron(TIME, "%m/%d/%Y %H:%M")
[1] (11/14/06 20:10:00)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

Use lubridate - it's a fantastic library that will save you much effort.

library(lubridate)
x <- "11/14/2006 20:10"
> mdy_hm(x)
[1] "2006-11-14 20:10:00 UTC"

All lubridate's time conversion function follow a very similar pattern: e.g. "2013-04-01" can be parsed with ymd, etc.

Victor K.
  • 4,054
  • 3
  • 25
  • 38
  • That does seem WAY easier. Unfortunately, I was specifically told to use the chron package. But I will definitely use this for my own reference! – Mike L Apr 26 '13 at 00:56
1

You can use as.POSIXct to convert string into time.

TIME <- "11/14/2006 20:10"
as.POSIXct(TIME, format="%m/%d/%Y %H:%M", tz='GMT')
## [1] "2006-11-14 20:10:00 GMT"
CHP
  • 16,981
  • 4
  • 38
  • 57