How To Change Date From Dd-month-yy To Yyyy-mm-dd In R

I recently had to work with dates in R, and I found myself needing to convert dates from the format “dd-month-yy” to “yyyy-mm-dd”. After some research and trial and error, I managed to figure it out. In this article, I’ll share the steps I took to accomplish this task, and I hope it helps you in your own date manipulation endeavors.

Using the lubridate package

In R, the lubridate package is incredibly helpful for working with dates. It makes date manipulation and parsing much easier and more intuitive. If you don’t have it installed already, you can do so by running the following command:

install.packages("lubridate")

Once the package is installed, you can load it into your R environment using:

library(lubridate)

Converting the date format

Assuming you have a vector of dates in the “dd-month-yy” format, you can use lubridate’s functions to convert them to “yyyy-mm-dd”. Here’s the step-by-step process:

  1. Step 1: Create a sample vector of dates in the “dd-month-yy” format:
  2. dates <- c("15-Jan-21", "28-Feb-22", "10-Dec-20")

  3. Step 2: Use the dmy() function from the lubridate package to parse the dates:
  4. parsed_dates <- dmy(dates)

  5. Step 3: Format the parsed dates into "yyyy-mm-dd" using the format() function:
  6. formatted_dates <- format(parsed_dates, "%Y-%m-%d")

Final Output

After following the above steps, the formatted_dates vector will contain the dates in the desired "yyyy-mm-dd" format.

Conclusion

Working with dates can be a bit tricky, but the lubridate package in R makes it much more manageable. By following these steps, you can easily convert dates from "dd-month-yy" to "yyyy-mm-dd" and carry on with your data analysis or visualization tasks without the headache of date formatting issues.