r - 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" 似乎会产生同样的结果,但它不会产生(例如)排序问题。
解决方案
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 或错误。对于时间课程也是如此。如果您没有数据,那么您可以只使用一些虚拟值,并使用格式仅打印您想要的字段。
推荐阅读
- ios - 代码点火器 - 无法连接:0 发送 ios 通知时
- mysql - 无法在 phpmyadmin - mysql 中添加外键约束
- regex - Regexp_like 与在线正则表达式验证器 - 不同的结果
- swift - 在 indexPath.row 的数组中快速打印元素
- c# - 如何在 Unity 中使用 C# 生成随机浮点数(Unity 拒绝大多数其他建议的答案)?
- react-native - 更新坐标数组时不呈现多条折线
- django - Django 忽略模型字段
- python - Python 数组和矩阵
- xcode - 在 Xcode 中错误地删除了整个项目的引用
- android - 如何从 sqlite 检索数据到 ListView