更改日期的打印格式而不将其转换为字符

rso*_*ren 5 r date

对于DateR 中的对象,是否可以"%Y-%m-%d"在保留其Date类的同时选择与默认值不同的打印格式?该format()函数将其转换回character字符串。

# 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"
Run Code Online (Sandbox Code Playgroud)

G. *_*eck 5

您可以使用自己的打印方法创建 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
Run Code Online (Sandbox Code Playgroud)