I need to map 3-4 different dataframes that have different date formats. How can we convert date in format:
YYYY-MM-DD
to character in the format:
MMM-YY
You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.
To format the dates in R, use the format() function. The format() method accepts an R object and the format in which we want the output. The format() method provides you with formatting an R object for pretty printing. The Dates in R are expressed as the number of days since 1970-01-01.
Date() is a built-in R function that converts between character representations and class “Date” objects representing the calendar dates. Dates are represented as the number of days since 1970-01-01, with negative values for earlier dates.
Create a date object from the string (skip this if your column is already in the Date format):
original_date <- as.Date("2017-07-19", "%Y-%m-%d")
Then format the original date to the new format:
format(original_date, "%b-%y")
# "Jul-17"
The %b
indicates the 3-letter abbreviation of the month and %y
is the year without the century. You can find more of these codes and their meaning here: http://strftime.org/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With