Search code examples
rdplyrstrptime

R strptime equivalent for use inside mutate with format="%Y%m%d%H%M%S"


Using R version 3.2.2, I'm trying to read time stamps in the form of "%Y%m%d%H%M%S" (e.g. "20131227185208") using mutate in the following code:

library("dplyr")
df <- data_frame(DTHR_EVENT="20131227185208")
mutate(df, DTHR_EVENT = strptime(DTHR_EVENT, "%Y%m%d%H%M%S"))

...but this generates the following error:

Error: mutate does not support POSIXlt results

Outside of mutate, strptime works fine like this:

> strptime("20131227185208", "%Y%m%d%H%M%S")
[1] "2013-12-27 18:52:08 EST"

But I need to apply it with mutate to convert all values from a column into a new one in a convenient way... If you have a better way than mutate, I welcome any suggestion.

For the record, I also tried the following alternatives, but each one fails differently:

df <- mutate(df, DTHR_EVENT = as.Date.POSIXlt(DTHR_EVENT, "%Y%m%d%H%M%S"))

Error: invalid 'x' argument

df <- mutate(df, DTHR_EVENT = as.POSIXct(DTHR_EVENT, format="%Y%m%d%H%M%S", origin="EST5EDT"))
 ==> DTHR_EVENT all set to NA

Solution

  • Just convert the POSIXlt data.type to POSIXct

    mutate(df, DTHR_EVENT = as.POSIXct(strptime(DTHR_EVENT, "%Y%m%d%H%M%S")))
    

    See this github issue