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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With