繁体   English   中英

将数据从 yyyyMM 转换为 yyyyQQ

[英]Converting data from yyyyMM to yyyyQQ

我的日期数据采用“yyyymm”格式,特别是 20071 / 20074 / 20077 / 200710。

我想将其转换为四分之一。

此外,在另一个数据集中,我有我想要汇总到季度的每月数据。 有功能吗?

在基础 R 中,您可以附加一个临时日期并从中提取年份和季度。

x <- as.character(c(20071, 20074, 20077, 200710))
temp <- as.Date(paste(x, "01"), "%Y%m %d")
paste(format(temp, "%Y"), quarters(temp))
#[1] "2007 Q1" "2007 Q2" "2007 Q3" "2007 Q4"

如果您想要季度作为数字,我们可以使用lubridate::quarter

paste(format(temp, "%Y"), lubridate::quarter(temp))
#[1] "2007 1" "2007 2" "2007 3" "2007 4"

yearqtr类在内部将年度和季度表示为一年加上一个分数(Q1 为 0,Q2 为 1/4,Q3 为 2/4,Q4 为 3/4)并显示如下:

library(zoo)
ym <- c(20071, 20074, 20077, 200710) # test data

yq <- as.yearqtr(as.character(ym), "%Y%m")
yq
## [1] "2007 Q1" "2007 Q2" "2007 Q3" "2007 Q4"

最好将其保留为yearqtr因为您可以对其执行许多操作(例如yq + 1/4是下一个季度),但如果您希望将其作为纯字符串使用format(yq)as.character(yq) .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM