R strptime 等价于在 mutate 中使用 format="%Y%m%d%H%M%S"

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

使用 R 版本 3.2.2,我尝试在以下代码中使用 mutate 以“%Y%m%d%H%M%S”(例如“20131227185208”)的形式读取时间戳:

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

...但这会产生以下错误:

Error: mutate does not support POSIXlt results

在 mutate 之外,strptime 可以像这样正常工作:

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

但我需要将它与 mutate 一起应用,以便以方便的方式将列中的所有值转换为新值...如果您有比 mutate 更好的方法,我欢迎任何建议。

郑重声明,我还尝试了以下备选方案,但每一种都失败了:

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

只需将 POSIXlt data.type 转换为 POSIXct

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

this github issue