Convert mm-yy character string to a date in R

133 Views Asked by At

I have a data frame with a column containing dates in the format of mm/yy. However, the column is character type and I would like to change it to a date for plotting purposes.

Example code below:

x <- c("01/20","02/20","03/20")
as.Date(x,format = "%m/%y")

I get the following error:

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

I would like to use as.Date if possible.

2

There are 2 best solutions below

0
On

One way to address it would be to add characters and then pass it to as.Date

x <- c("01/20","02/20","03/20")
as.Date(paste0("01/",x),format = "%d/%m/%y")  
0
On

Is it suitable?

x <- c("01/20","02/20","03/20")
as.Date.character(paste0('01/', x), '%d/%m/%y')
[1] "2020-01-01" "2020-02-01" "2020-03-01"