GNU Rで月次データを四半期に集約する

時系列解析で月次データを四半期に集約する(3ヶ月の合計や平均を計算する)ことはよくある。以下はstats, zoo, xtsを使った場合。

まず準備:

# 2010年1月から12月までの月次データを生成する
rm(list=ls())
dataLength <- 12
set.seed(1) # to make it reproducible
data1 <- rnorm(dataLength)

statsのtsオブジェクトに対してstatsのaggregateを使う場合:

dataMonthTs <- ts(data1, start=c(2010,1), frequency=12)
dataQuartTs <- aggregate(dataMonthTs, nfrequency = 4, FUN = sum)
dataQuartTs

以上のやり方はzooもxtsもなかった10年以上前にはよく使われていた。ただし、最近は以下のようにzooやxtsを使うほうが一般的かもしれない。

zooオブジェクトに対してzooのaggregateを使う場合:

library(zoo)
dateZoo <- seq(as.Date("2010-01-01"), as.Date("2010-12-01"), by = "month")
dataMonthZoo <- zoo(data1, dateZoo)
dataQuartZoo <- aggregate(dataMonthZoo, as.yearqtr, sum)
dataQuartZoo

zooオブジェクトに対してxtsのapply.quarterlyを使う場合:

library(xts)
dataQuartXts <- apply.quarterly(dataMonthZoo, sum)
dataQuartXts

# ただし、四半期の日付が2010-03-01 2010-06-01等となって日付がふさわしくない。
# たとえば、以下のようにして日付2010-01-01 2010-04-01等と直す。
time(dataQuartZoo) <- as.Date(as.yearqtr(time(dataQuartZoo)))
dataQuartZoo
#それ以外だとto.quarterlyを使う方法も考えられる。

その他にもRmetricsのtimeSeriesの関数を使うなどのやり方もあると思います。よりエレガントなやり方があったらコメントで教えて下さい。

[参考]
R - Set the first month of each quarter as the index after applying apply.quarterly() - Stack Overflow
http://stackoverflow.com/questions/19352828/set-the-first-month-of-each-quarter-as-the-index-after-applying-apply-quarterly
Kobe.R: Kobe.R #10 xts 時系列の簡単操作
http://kobexr.blogspot.jp/2014/10/kober-10-xts.html