Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change print format of a Date without converting it to character

Tags:

date

r

With a Date object in R, is it possible to choose a different print format than the default "%Y-%m-%d" while keeping its Date class? The format() function converts it back to a character string.

# 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 the Date class, but with the original format
# format() converts it back to a character variable
str(format(date, "%d-%m-%Y"))
# chr "01-05-2015"
like image 241
rsoren Avatar asked Jan 06 '15 01:01

rsoren


1 Answers

You can create a subclass of Date with its own print method but its probably not worth it.

If you use chron then 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
like image 102
G. Grothendieck Avatar answered Oct 06 '22 15:10

G. Grothendieck