使用R中的日期对象,是否可以选择与默认“%Y-%m-%d”不同的格式,同时保留日期对象? format()
函数将其转换回字符串。
# 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"
答案 0 :(得分:3)
您可以使用自己的print方法创建Date的子类,但它可能不值得。
如果您使用chron,则可以将格式与每个对象相关联:
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