0

I'm looking for a way to convert a chr to date. The current format of the csv is like this: "Jul 6, 2004"

when I try

df$Date <- as.Date(df$Date) 

I get this error:

Error in charToDate(x) : character string is not in a standard unambiguous format

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
Vegas588
  • 279
  • 5
  • 18

2 Answers2

2

You need to specify the format of your date string, e.g. in your case

ss <- "Jul 6, 2004"   
as.Date(ss, format = "%b %d, %Y")
#[1] "2004-07-06"

See ?Date for details, and ?strptime for a description of all conversion specifications.

If format is not explicitly given, as.Date (by default) assumes the string to be in either "%Y-%m-%d" or "%Y/%m/%d" format.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

We can also use lubridate:

test<-"Jul 6, 2004"
lubridate::mdy(test)
#[1] "2004-07-06"
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • I want to follow up on this as still not solved. The column has two distinct formats. One is "Jun 30, 2019" or just the Year such as 2021. I guess I need a more advanced function or something to correct the column given that either format could be encountered. – Vegas588 Mar 16 '19 at 19:39
  • You can and should ask a nnew question. It's difficult to know what the goal is,sorry. – NelsonGon Mar 17 '19 at 04:53
  • 1
    Figured it out with some outside help. Since the column has two distinct formats, we realized the easiest way to clean it up was to take the last 4 characters in the column. That was the key because it was the common link between the two formats. – Vegas588 Mar 19 '19 at 13:45