Forklift17
Forklift17

Reputation: 2477

as.POSIXct turns a tibble of times into a bunch of numbers

I have a tibble my_column with a column of strings like this:

'1/25/2018 0:00:00'
'11/14/2019 14:25:00'
'4/7/2019 9:31:53'

When I run

lapply(my_column, as.POSIXct, format="%m/%d/%Y %H:%M:%S")

I get back a bunch of large numbers, not datetimes like I want it. What is causing this undesired behavior, and how do I fix it?

Upvotes: 0

Views: 184

Answers (1)

rodolfoksveiga
rodolfoksveiga

Reputation: 1261

You don't need to use lapply(), because asPOSIXct() is a vectorized function, as many of the R's functions. When you use lapply(), the outputs are stored inside a list and you'll have problems to assign it as a table column.

If you want to return a vector, so you can assign it to your table column, you can do:

df$my_column = as.POSIXct(df$my_column, format = "%m/%d/%Y %H:%M:%S")

Or you can use lubridate library, which is slightly more efficient. Like this:

library(lubridate)
df$my_column <- parse_date_time(df$my_column, '%m/%d/%y %H:%M:%S')

Here is the output:

[1] "2018-01-25 00:00:00 -02" "2019-11-14 14:25:00 -03" "2019-04-07 09:31:53 -03"

Note the difference between the output as a vector (using vectorized function) and the output when using lapply(), as follows:

[[1]]
[1] "2018-01-25 -02"

[[2]]
[1] "2019-11-14 14:25:00 -03"

[[3]]
[1] "2019-04-07 09:31:53 -03"

Upvotes: 2

Related Questions