将每月列值汇总为季度值 [英] Aggregating monthly column values into quarterly values

查看:53
本文介绍了将每月列值汇总为季度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我对R完全陌生,我们将不胜感激。从2004年到2013年,我每个月都有以下数据(称为抑郁症汇总):

 月年抑郁量
1 01 2004 285
2 02 2004 323
3 03 2004 267
4 04 2004 2004 276
5 05 2004 312
6 06 2004 232
7 07 2004 228
8 08 2004 280
9 09 2004 277
10 10 2004 335
11 11 2004 2004 273
解决方案

1)如果 DF 是输入data.frame,将其转换为带有 yearmon 索引的动物园对象 z ,然后将其汇总为 yearqtr

 库(动物园)

toYearmon <-函数(y,m)as.yearmon(paste(y,m,sep =-))
z <-read.zoo(DF,index = 2:1,FUN = toYearmon)
ag<-合计(z,as.yearqtr,和)

给予:

 > ag 
2004 Q1 2004 Q2 2004 Q3 2004 Q4
875820785608

2)也可以:

 库(动物园)

yq<-as.yearqtr(as.yearmon(paste(DF $ Year,DF $ Month),%Y%m))
ta <-tapply(DF $ DepressionCount,yq,sum)


Hello Everybody I am pretty much completely new to R and any help is greatly appreciated. I have the following data (called "depressionaggregate") from 2004 until 2013 for each month:

    Month   Year    DepressionCount
1   01      2004    285
2   02      2004    323
3   03      2004    267
4   04      2004    276
5   05      2004    312
6   06      2004    232
7   07      2004    228
8   08      2004    280
9   09      2004    277
10  10      2004    335
11  11      2004    273

I am trying to create a new column with the aggregated values for each year for each quarter (i.e. 2004 Q1, 2004 Q2 etc.). I have tried using the function aggregate but have not been successful. Hope you can help me! Regards

解决方案

1) If DF is the input data.frame convert it to a zoo object z with a "yearmon" index and then aggregate that to "yearqtr":

library(zoo)

toYearmon <- function(y, m) as.yearmon(paste(y, m, sep = "-"))
z <- read.zoo(DF, index = 2:1, FUN = toYearmon)
ag <- aggregate(z, as.yearqtr, sum)

giving:

> ag
2004 Q1 2004 Q2 2004 Q3 2004 Q4 
    875     820     785     608 

2) This would also work:

library(zoo)

yq <- as.yearqtr(as.yearmon(paste(DF$Year, DF$Month), "%Y %m"))
ta <- tapply(DF$DepressionCount, yq, sum)

这篇关于将每月列值汇总为季度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆