为什么不能在tbl_df中转换日期?

时间:2015-07-09 22:17:39

标签: r dplyr lubridate

我有一个名为x的变量,如下所示:

x <- structure(list(Time = c("2002-05-07 21:00", "2002-05-08 21:00", 
                             "2002-05-09 21:00", "2002-05-10 21:00", 
                             "2002-05-11 21:00", "2002-05-13 21:00", 
                             "2002-05-14 21:00", "2002-05-15 21:00",
                             "2002-05-16 21:00", "2002-05-17 21:00")), 
               .Names = "Time", class = c("tbl_df", "data.frame"), 
               row.names = c(NA, -10L))

现在,我想将x中的字符串转换为日期,因为x[1,1] %>% lubridate::ymd_hm()为我提供了单个元素的预期结果,我认为以下方法可以解决问题:< / p>

x %>% lubridate::ymd_hm()

但它不起作用(结果是NA),我得到以下警告:

    Warning message:
    All formats failed to parse. No formats found.

为什么x %>% lubridate::ymd_hm()按照我的预期方式工作?我该怎样做才能得到我想要的结果?

2 个答案:

答案 0 :(得分:3)

函数mutate有效。

x %>% mutate(Time = ymd_hm(Time))

答案 1 :(得分:3)

这成功了(警告说我不明白,但我怀疑该对象的rownames可能与它有关。):

x %>% lubridate::ymd_hm(.$Time)
 [1] NA                        "2002-05-07 21:00:00 UTC" "2002-05-08 21:00:00 UTC"
 [4] "2002-05-09 21:00:00 UTC" "2002-05-10 21:00:00 UTC" "2002-05-11 21:00:00 UTC"
 [7] "2002-05-13 21:00:00 UTC" "2002-05-14 21:00:00 UTC" "2002-05-15 21:00:00 UTC"
[10] "2002-05-16 21:00:00 UTC" "2002-05-17 21:00:00 UTC"

x[1,1] %>% lubridate::ymd_hm() 
#[1] "2002-05-07 21:00:00 UTC"