Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

r - Aggregating monthly column values into quarterly values

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...