3

I have a column full of dates in format "mmm dd,yyyy".

They look like these: "Dec 21, 2015" "Aug 23, 2018" etc.

I tried to convert those dates to a proper date format for further data processing by doing as.Date("Dec 21, 2015") or as.Date(as.character("Dec 21, 2015"))but neither worked.

Here is the error message: Error in charToDate(x) : character string is not in a standard unambiguous format

I am wondering what is a good way to properly convert such nonstandard data format into proper data format and class "YYYY-MM-DD" (e.g. "2015-12-21")? Should I use regex syntax to solve that?

Thanks so much for your help!

Phil
  • 7,287
  • 3
  • 36
  • 66
DPatrick
  • 421
  • 3
  • 19

3 Answers3

4

Using lubridate:

library(dplyr)
library(lubridate)
df <- data.frame(date = c('Dec 21, 2015','Aug 23, 2018'))
df
          date
1 Dec 21, 2015
2 Aug 23, 2018
df %>% mutate(date1 = mdy(df$date))
          date      date1
1 Dec 21, 2015 2015-12-21
2 Aug 23, 2018 2018-08-23
Karthik S
  • 11,348
  • 2
  • 11
  • 25
2

Using base:

x <- "Dec 21, 2015"

as.Date(x, "%b %d, %y")
#> [1] "2020-12-21"

Created on 2020-11-16 by the reprex package (v0.3.0)

Depending on what your date variable is named, it can look something like this:

df$date <- as.Date(df$date, "%b %d, %y")
Eric
  • 2,699
  • 5
  • 17
2

An option with anydate from anytime

library(anytime)
df$date <- anydate(df$date)
df$date
#[1] "2015-12-21" "2018-08-23"

data

df <- data.frame(date = c('Dec 21, 2015','Aug 23, 2018'))
akrun
  • 874,273
  • 37
  • 540
  • 662