我有一个名为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()
按照我的预期方式工作?我该怎样做才能得到我想要的结果?
答案 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"