mike.dl mike.dl - 1 month ago 16
R Question

convert different string types in dates R data frame

I have a messy data frame with two columns:

DF<-data.frame(x=seq(100,105,1),y=c("3/25/2014 12:56","3/25/2014 14:18","3/25/2014 14:18","3/25/2014 14:18","3/25/2014 14:18","2014-03-25 14:19:08.043"))

x y
1 100 3/25/2014 12:56
2 101 3/25/2014 14:18
3 102 3/25/2014 14:18
4 103 3/25/2014 14:18
5 104 3/25/2014 14:18
6 105 2014-03-25 14:19:08.043


I want to convert the y columns into R dates so to have:

x y
1 100 2014-03-25
2 101 2014-03-25
3 102 2014-03-25
4 103 2014-03-25
5 104 2014-03-25
6 105 2014-03-25


In order to do so, I can use the function parse_date_time from Lubridate for the first 5 elements

as.Date(parse_date_time(DF$y[1:5], orders="mdy hm"))


and directly the function as.Date for the last one:

as.Date(DF$y[6], orders="mdy hm")


I could do that by making a for and if loop, however, I'm looking for a more elegant vectorised solution.

Do you have an idea?

Thanks

Answer

I'd use package anytime:

library(anytime)
anydate(DF$y)
#[1] "2014-03-25" "2014-03-25" "2014-03-25" "2014-03-25" "2014-03-25" "2014-03-25"