I have a small problem. My dates consist of 2 different formats:
- m/d/y
- m.d.y
Now I want to convert the whole data set into m/d/y I tried using:
df$YEAR <- as.Date(df$YEAR, format = "%m/%d/%Y")
But now I have the problem that all of the m.d.y date types are now seen as "NA" values. Another problem that arose is that the date now begins with the year even though I wanted it to appear at the end.
NA NA "2003-01-01"
What should I do?
CodePudding user response:
I like the lubridate library in tidyverse. You can use lubridate first to get all the dates into one format, and then reformat them as you like.
library(dplyr)
library(lubridate)
dates<-c("12.25.2021","12/26/2021")
new_date=mdy(dates) %>% format(format="%m/%d/%Y")
[1] "12/25/2021" "12/26/2021"
CodePudding user response:
You may define multiple formats in format=
.
x <- c('12/28/2021', '12.28.2021', '2021-12-28')
as.Date(x, format=c("%m/%d/%Y", "%m.%d.%Y", "%F"))
# [1] "2021-12-28" "2021-12-28" "2021-12-28"