mauna
mauna

Reputation: 1118

Why can't lubridate convert dates in a tbl_df?

I have a variable named x that is like this:

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))

Now, I'd like to convert the strings in x into dates and since x[1,1] %>% lubridate::ymd_hm() gives me the expected result for a single element, I thought the following would do the trick:

x %>% lubridate::ymd_hm()

But it does not work (result is NA) and I get the following warning:

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

Why doesn't x %>% lubridate::ymd_hm() work the way I had expected it and what can I do to get the result I want?

Upvotes: 0

Views: 384

Answers (2)

IRTFM
IRTFM

Reputation: 263301

This succeeds (with a warning that I don't understand but I suspect that the rownames of that object may have something to do with it.):

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"

Upvotes: 3

Pierre L
Pierre L

Reputation: 28441

The function mutate works.

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

Upvotes: 3

Related Questions