首页 > 解决方案 > R: 为什么 '%b.%Y' 日期类不是“日期”?

问题描述

有时我会处理这样的数据:

sep-2018

从这样的日期开始:

Sys.Date()
[1] "2018-09-21"

为了得到这个结果,我通常使用:

format(Sys.Date(),'%b-%Y')

但它class不是日期:

 class(format(Sys.Date(),'%b-%Y'))
[1] "character"

为什么不是约会?是否可以与class()=一起使用date,以及如何使用?

像动物园这样的外部库也有同样的东西。

library(zoo)
> class(format(as.yearmon(format(Sys.Date()), "%Y-%m-%d"), "%b.%Y"))
[1] "character"

同样使用 "%m.%Y" 似乎会产生同样的结果,但它不会产生(例如)排序问题。

标签: rdate

解决方案


format 命令获取日期并根据您提供的格式输出可打印的字符串。引用文档:

An object of similar structure to x containing character representations of the 
elements of the first argument x in a common format, and in the current 
locale's encoding.

此外,日期变量在内部存储为数字类型(自 1970-01-01 以来的天数)

dput(Sys.Date())
#structure(17795, class = "Date")

structure(0, class = "Date")
#[1] "1970-01-01"

因此,要确定日期,您需要日、月和年字段。如果您没有全部三个,它可能会返回 NA 或错误。对于时间课程也是如此。如果您没有数据,那么您可以只使用一些虚拟值,并使用格式仅打印您想要的字段。


推荐阅读