Michael Discenza Michael Discenza - 2 months ago 23
R Question

R Date time conversion - lapply and unlist is converting to days after the epoch

I am converting a string for dates that look like

12/8/12
, probably in a rather roundabout way by 1) adding leading zeros (zero padding) to the day and month numbers and then converting to date object using the
as.Date
function in a custom function that I wrote.

date_conversion <- function(date_string){
split <- unlist(strsplit(date_string, "/"))
split[1] = str_pad(split[1], 2, pad = "0")
split[2] = str_pad(split[1], 2, pad = "0")
t = as.Date(paste(split, collapse = "/"),format='%m/%d/%y')
return (t)
}


What's very confusing is that I can get back the result that I think I want when I call the function on one input:

> date_conversion(test[1])
[1] "2012-12-12"
> typeof(date_conversion(test[1]))
[1] "double"


Then when I use
lapply
, it returns this string representation:

> lapply(test, date_conversion)
[[1]]
[1] "2012-12-12"

[[2]]
[1] "2015-12-12"

[[3]]
[1] "2015-09-09"


Then when I call
unlist
, the dates are changed into days since the epoch:

unlist(lapply(test, date_conversion))
[1] 15686 16781 16687


I guess the underlying representation of the date is days since the epoch (hence
typeof
returns double, but why would the list value show the dates formatted in more human readable form and then calling
unlist
make them go to back to this days since the epoch form?

Also, is there a elegant way for me to do a conversion like this? Maybe I shouldn't be using Lapply?

J_F J_F
Answer

There is another solution with the lubridatepackage:

test <- c("12/8/12", "1/1/13", "2/4/13")

dates <- lubridate::mdy(test)
##[1] "2012-12-08" "2013-01-01" "2013-02-04"

class(dates)
##Date[1:3], format: "2012-12-08" "2013-01-01" "2013-02-04"

str(dates)
##[1] "Date"

The lubridate function mdy() converts the strings in your object test into month (m), days (d) and years (y). If your object test is a list, the same answer as aichao wrote, is possible with lubridate::mdy((unlist(test)).