Hi :) I have a column of my data.frame which contains dates in two formats. Here is an short minimal example:
D = data.frame(dates = c("3/31/2016", "01.12.2015"))
dates
1 3/31/2016
2 01.12.2015
With the nice function strptime
I can easily get date-times for each format:
D$date1 <- strptime(D$dates, format = "%m/%d/%Y")
D$date2 <- strptime(D$dates, format = "%d.%m.%Y")
I already managed a workaround with:
D$date12 <- do.call(pmin, c(D[c("date1","date2")], na.rm=TRUE) )
To achieve this:
dates date1 date2 date12
1 3/31/2016 2016-03-31 <NA> 2016-03-31
2 01.12.2015 <NA> 2015-12-01 2015-12-01
Is there are more sophisticated way to do this transformation (from dates to date12) at once?
Regards
You can use the anytime
package.
library(anytime)
anytime::addFormats("%d.%m.%Y")
anydate(D$dates)
Note that the argument in anydate
has to be a vector, so just select the coloumn dates
.
Or use lubridate
parse_date_time(D$dates, c("mdy", "dmy"))