按月份的时间序列聚合(R)
在mydataset中,日期为天格式。我需要把它汇总成月份格式。 为了清楚起见,这里是mydataset按月份的时间序列聚合(R),r,dataframe,time-series,R,Dataframe,Time Series,在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(2
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的总和。
在输出中,我希望使用这种格式
2015年1月3550日(2015年1月Y变量之和)
2015年2月4000日(2015年2月Y变量之和)
怎么做?
我试着在这里这样做,但没用。
如何更正?我们创建了一个年+月的分组变量,然后进行
求和
library(tidyverse)
library(zoo)
mydat %>%
group_by(yearMon = as.yearmon(dmy(date))) %>%
summarise(Y = sum(Y))
下面是一个使用聚合的基本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\u year
成分,并使用aggregate
按month\u year
求和Y
样本数据
mydat1)数据。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
给这个动物园对象:
Y
## Jan 2015
## 3550
虽然不需要,但如果要将其转换回数据帧,请参见?fortify.zoo
3)xts/zoo
转换为xts时间序列表示法x
,然后使用aggregate.zoo
创建zoo对象z
<代码>fmt
来自上面
library(zoo)
Y <- read.zoo(mydat, FUN = as.yearmon, format = fmt, aggregate = sum)
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
library(xts)#也在动物园里
谢谢你快速而有用的回答谢谢,你的回答也很有用:)
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