[英]time series aggregation by month in R
在mydataset中,日期格式的日期。 我需要将它汇总到月份格式。 说清楚,这里是mydataset。
mydat
structure(list(date = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("12.01.2015", "13.01.2015",
"14.01.2015", "15.01.2015"), class = "factor"), Y = c(200L, 50L,
100L, 50L, 200L, 200L, 50L, 200L, 100L, 1000L, 1000L, 50L, 50L,
100L, 200L)), .Names = c("date", "Y"), class = "data.frame", row.names = c(NA,
-15L))
聚合必须通过Y.在输出中的总和我期望这种格式01.2015 3550(2015年1月的Y变量之和)02.2015 4000(2015年2月的Y变量之和)
怎么做? 我尝试这样做这里按月R聚合时间序列对象 ,但它没有帮助我。 怎么回事?
以下是使用aggregate
的基本R解决方案:
with(mydat, aggregate(
Y,
list(month_year = format(as.POSIXct(date, format = "%d.%m.%Y"), "%m/%Y")),
sum))
# month_year x
#1 01/2015 3550
说明:从date
提取month_year
组件,并使用aggregate
month_year
与Y
month_year
。
mydat <- structure(list(date = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("12.01.2015", "13.01.2015",
"14.01.2015", "15.01.2015"), class = "factor"), Y = c(200L, 50L,
100L, 50L, 200L, 200L, 50L, 200L, 100L, 1000L, 1000L, 50L, 50L,
100L, 200L)), .Names = c("date", "Y"), class = "data.frame", row.names = c(NA,
-15L))
我们创建一个年份+月份的分组变量,然后进行sum
library(tidyverse)
library(zoo)
mydat %>%
group_by(yearMon = as.yearmon(dmy(date))) %>%
summarise(Y = sum(Y))
1)data.frame使用aggregate
和"yearmon"
类分组变量:
library(zoo)
fmt <- "%d.%m.%Y"
aggregate(mydat["Y"], list(Date = as.yearmon(mydat$date, fmt)), sum)
## Date Y
## 1 Jan 2015 3550
2)zoo您可以考虑使用时间序列表示而不是数据帧。 这使得许多时间序列操作更容易。 这里我们使用read.zoo
将mydat
转换为zoo对象。 fmt
来自上方。
library(zoo)
Y <- read.zoo(mydat, FUN = as.yearmon, format = fmt, aggregate = sum)
给这个动物园对象:
Y
## Jan 2015
## 3550
虽然不必要,但如果要将其转换回数据框,请参阅?fortify.zoo
。
3)xts / zoo
转换为xts时间序列表示x
,然后使用aggregate.zoo
创建动物园对象z
。 fmt
来自上方。
library(xts) # also pulls in zoo
x <- xts(mydat["Y"], as.Date(mydat$date, fmt))
z <- aggregate(x, as.yearmon, sum)
z
##
## Jan 2015 3550
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.