-1

I have a column currentdate with date in class factor and formatted as 1/1/2017. I want to convert the dates to 2017-01. My code below gives and error:

Code:

data$NewDate <- format(as.Date(data$currentdate), "%Y-%m")

Error:

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

How do I fix that?

PKumar
  • 10,971
  • 6
  • 37
  • 52
Pat Ca
  • 11
  • 3

2 Answers2

0

It's likely that your data$currentdate is not in a unambiguous format, and needs to be specified in the as.Date().

Something like this:

format(as.Date("01/01/2017", format="%m/%d/%Y"), "%Y-%m")
John Harley
  • 156
  • 1
  • 6
0

You need to specify the date format in as.Date(), since it cannot guess by the numbers if it's day/month/year or month/day/year:

dates <- c('1/1/2017', '12/1/2017', '1/10/2017', '11/10/2017')

format(as.Date(dates, '%d/%m/%Y'), '%Y-%m')

If you need to store the values as date/time, use class POSIXct:

newdates <- as.POSIXct(dates, format = '%d/%m/%Y')

Then specify the format when displaying the data:

format(newdates, '%Y-%m')