Search code examples
rdatedata-cleaning

How to convert a Date column currently as 01/01/00 to 01/01/2000


I am working a dataset which has a Date column currently stored as Character, below is the format of how the dates are:

31/12/00

01/01/01

I want to change the year part from "00" to "2000" and "01" to "2001" for the whole column and want it in date format.

How can I do it?

enter image description here

I tried doing the following way

if(y2k_clean$Date[7:8] == "00")
  replace(y2k_clean$Date, 7, "2000")

I also tried to achieve this with gsub() but could not get the result I wanted.

Thank you.


Solution

  • You could first convert it to a date with the format and after that convert it to your format with %Y as 4 digit year like this:

    dates <- c('31/12/00', '01/01/01')
    format(as.Date(dates,format='%d/%m/%y'), "%d/%m/%Y")
    #> [1] "31/12/2000" "01/01/2001"
    

    Created on 2022-12-16 with reprex v2.0.2