R Converting to date from multiple formats

I need to convert a date string that matches valid dates in multiple formats.

eg.

dates <- c("01-01-2017","02-01-2017","12-01-2016","20160901","20161001", "20161101")

> as.Date(dates, format=c("%m-%d-%Y","%Y%m%d"))
[1] "2017-01-01" NA           "2016-12-01" "2016-09-01" NA           "2016-11-01"

      

two dates show that NA

+3


source to share


2 answers


This is pretty much what I wrote the anytime package for:

R> dates <- c("01-01-2017","02-01-2017","12-01-2016","20160901","20161001", 
+             "20161101")
R> library(anytime)
R> anydate(dates)
[1] "2017-01-01" "2017-02-01" "2016-12-01" "2016-09-01" 
[5] "2016-10-01" "2016-11-01"
R> 

      



Reasonable and without explicit formatting, source, or other line noise.

Speaking of which, a non-starting ISO style with a year requires potential problems, so it 02-03-2017

could be Feb 3rd or March 2nd. I follow the North American convention, which I also find to be somewhat broken - but it is so damn prevalent. Do yourself a favor and try to restrict your data entry to ISO dates, at least in ISO order YYYYMMDD.

+7


source


Try this after your initial idea



as.Date(dates, tryFormats = c("%m-%d-%Y", "%Y%m%d"))

      

0


source







All Articles