How to change default “date” format in R?

The default R date format is "yyyy-mm-dd".

Let say I have dataset

library(data.table)

dt_test <- data.table(
  date = c("01.03.2019", "02.03.2019"),
  value = c(1, 2))

where "date" is "chr" type.

I'd like to have it as "Date" feature and set default date format as "%d.%m.%Y".

And, also to keep this format for all "ggplot" operations.

Thanks all ahead!

Dates are actually stored as integers. The format options are for printing, not for storing the date values.

dt_test <- data.table(
  date = as.Date(c("01.03.2019", "02.03.2019"), format = "%d.%m.%Y"), 
  value = c(1, 2))

You will have to define your desired date format when you want to display the date values, e.g. in your plots. You can use the format above or use lubridate.

You can specify your date format in ggplot with scale_x_date()

library(data.table)
library(ggplot2)
dt_test <- data.table(
    date = as.Date(c("01.03.2019", "02.03.2019"), format = "%d.%m.%Y"), 
    value = c(1, 2))
ggplot(dt_test, aes(date, value)) +
    geom_line()+
    scale_x_date(date_labels = '%d.%m.%Y')

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.