In R, change the format of a date object without converting it to a character

With a date object in R, can I choose a different format than the default value "% Y-% m-% d", while remaining a date object? The function format()converts it back to a string of characters.

# I start with a character string and convert it to a date
> date_char <- "01-05-2015"
> date <- as.Date(date_char, format = "%d-%m-%Y")

> # By default, R re-formats the date as "%Y-%m-%d"
> date
 [1] "2015-05-01"

> # I want to keep it as a date object, but with the original format
> # format() converts it back to a character variable
> str(format(date, "%d-%m-%Y"))
 chr "01-05-2015"
+4
source share
1 answer

You can subclass Date with your own printing method, but it's probably not worth it.

If you use chron, you can associate a format with each object:

library(chron)

c1 <- chron(c("02/27/92", "02/27/92", "01/14/92")); c1
## [1] 02/27/92 02/27/92 01/14/92

c2 <- chron(c("02/27/92", "02/27/92", "01/14/92"), out.format = "y-mmm-d"); c2
## [1] 1992-Feb-27 1992-Feb-27 1992-Jan-14
+3
source

Source: https://habr.com/ru/post/1570086/


All Articles