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

标签 r date

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/

相关文章:

r - 如何在ggplot中一次绘制多列

r - 使用 API key 在 ggmap 中映射时出错(403 Forbidden)

java - 日期和时间相减

R Package "rvest"无法安装,与 Ubuntu 终端中的情况相同

r - 为什么 R.Version() 返回 "language"字符串?

php - 查看过去24h是否有记录

mysql - 按帮助分组(按多个分组,有重复)

ruby-on-rails - Rails 4 中的最佳日期验证?

r - 使用鼠标点击 Shiny 的交互式绘图

javascript - 使用 JavaScript 从时间戳获取星期几