Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to character in particular format In R

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
like image 852
eclairs Avatar asked Jul 19 '17 12:07

eclairs


People also ask

How do I convert a date to a character?

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.

How do you specify date format in R?

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.

Is date a character in R?

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.


1 Answers

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/

like image 105
Paolo Avatar answered Sep 18 '22 17:09

Paolo