Lellekert
Lellekert

Reputation: 23

Possible to have date variable in day-month-year format in R?

I'm making a 'Make your own graph tutorial' using Rmarkdown, I have a dataset with a date variable (format: day-month-year), using dmy(variable) I can correctly class the variable as a 'Date' variable (format:year-month-day).

Users have to filter based on this date, and seeing as Dutch people use the day-month-year format I want to allow them to filter based on this format. (I could simply tell them to filter in the year-month-day format but this complicates the exercise.)

Goal of question: getting R to recognize a variable as date, but using a day-month-year format

date <- "28-02-2020"
date <- as.Date(date, "%d-%m-%Y")
class(date)

again: date now gives "2020-02-28" - I want "28-02-2020" (with class: Date)

Upvotes: 2

Views: 966

Answers (1)

desval
desval

Reputation: 2435

As far as I understand, no, it is not possible.

Internally, R stores dates as the number of days since January 1, 1970, and prints them out in format "YYYY-mm-dd". Given that people use different formats around the world, it would be really messy if it would be otherwise.

As a side note, if you need to plot your data, ggplot2 gives you the option to properly format your dates, without having to transform them into characters or factors.

As a side note 2, base r lets you adjust the format of the date, and this depends on the system locale that are available, which you can set (this is different on different systems, I am using ubuntu):

Sys.setlocale("LC_TIME", "en_US.utf8")
format(Sys.Date(), format = "%Y-%b-%d")
[1] "2020-May-01"

Sys.setlocale("LC_TIME", "de_CH.utf8")
format(Sys.Date(), format = "%Y-%b-%d")
[1] "2020-Mai-01"

See more info here:

How to change the locale of R?

How to set the default language of date in R

Upvotes: 1

Related Questions