r - 合并数据框以创建分组时间序列
问题描述
我想创建一个分组的时间序列(层次结构)。基本上每年有四个季度和 12 个月。年份是总计,季度是月份的小计。月份是最低值。我正在尝试使用Robert Handyman()gts
的库:在这里,但我在某处遗漏了一些东西。初步演示数据如下所示。hts
forecast
library(tidyr)
表格1:
ts(rnorm(67), start=c(2015, 4),frequency=12)
表2:
aggregate(ts(rnorm(67), start=c(2015, 4), frequency=12), nfrequency=4)
任何建议如何将列创建为年度总计,然后按季度汇总,并表示月份。这些本质上意味着,数据集上有年-季-月的层次结构。
解决方案
如果您不喜欢坚持该ts()
格式,您可以将其放入数据集并使用 , 中的函数zoo
并lubridate
进行dplyr
所需的输出。
library(dplyr)
library(zoo)
library(tibble)
library(lubridate)
x <- ts(rnorm(67), start=c(2015, 4),frequency=12)
dat <- tibble(
# change time of the ts object into year-month
# and extract just the month
m = month(as.yearmon(time(x))),
# change time of the ts object to year-month
# and extract the year
year = year(as.yearmon(time(x))),
# change time of the ts object to year-month
# and extract the quarter
qtr = quarter(as.yearmon(time(x))),
value = as.vector(x)) %>%
# group data by year and quarter
group_by(year, qtr) %>%
# get the sum of value for each year-quarter.
mutate(qtr_sum = sum(value)) %>%
# ungroup the data and then group again just by year
ungroup() %>%
group_by(year) %>%
# calculate the yearly sum
mutate(yr_sum = sum(value))
dat
# # A tibble: 67 x 6
# # Groups: year [6]
# m year qtr value qtr_sum yr_sum
# <dbl> <dbl> <int> <dbl> <dbl> <dbl>
# 1 4 2015 2 0.555 -1.68 -0.851
# 2 5 2015 2 -0.767 -1.68 -0.851
# 3 6 2015 2 -1.47 -1.68 -0.851
# 4 7 2015 3 -1.75 -0.0733 -0.851
# 5 8 2015 3 1.26 -0.0733 -0.851
# 6 9 2015 3 0.408 -0.0733 -0.851
# 7 10 2015 4 -0.0731 0.905 -0.851
# 8 11 2015 4 0.824 0.905 -0.851
# 9 12 2015 4 0.154 0.905 -0.851
# 10 1 2016 1 -0.231 -0.634 2.70
# # … with 57 more rows
推荐阅读
- sql - 需要有关 SQL Server 表值函数格式的帮助
- sql - SQL Server 查找接近服务日期和月份的行
- python - 类型错误:+ 不支持的操作数类型:“NoneType”和“str”退出状态 1
- shell - 在 shell 脚本文件中使用 mutt 发送邮件
- python - for循环特定时间间隔
- yii2 - 图像存在于文件夹中但不显示 yii2 高级
- javascript - 在选定的特定图像上添加叠加层(不超过 3 个)
- javascript - 忽略大小写sql查询
- azure-active-directory - .NET Core 3.1 到 .NET 5 的迁移 - Microsoft Identity Web Platform 停止工作
- java - ObjectMapper 类构造