带 Date
R 中的对象,是否可以选择与默认值不同的打印格式 "%Y-%m-%d"
同时保持其Date
类(class)? 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"
最佳答案
您可以使用自己的打印方法创建 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
关于r - 更改日期的打印格式而不将其转换为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27790647/