季節的な要素 (周期的に繰り返されるイベント) だけでなく、傾向 (標準の緩やかな変化) もうまく処理できるアプローチはstl()
、特に Rob J Hyndman によって実装されたものです。
decomp
Hyndman が提供する関数 (以下に再現) は、時系列をチェックしてから、季節 (存在する場合)、seasonality
、およびコンポーネントに変換するのに非常に役立ちます。decomposing
trend
residual
decomp <- function(x,transform=TRUE)
{
#decomposes time series into seasonal and trend components
#from http://robjhyndman.com/researchtips/tscharacteristics/
require(forecast)
# Transform series
if(transform & min(x,na.rm=TRUE) >= 0)
{
lambda <- BoxCox.lambda(na.contiguous(x))
x <- BoxCox(x,lambda)
}
else
{
lambda <- NULL
transform <- FALSE
}
# Seasonal data
if(frequency(x)>1)
{
x.stl <- stl(x,s.window="periodic",na.action=na.contiguous)
trend <- x.stl$time.series[,2]
season <- x.stl$time.series[,1]
remainder <- x - trend - season
}
else #Nonseasonal data
{
require(mgcv)
tt <- 1:length(x)
trend <- rep(NA,length(x))
trend[!is.na(x)] <- fitted(gam(x ~ s(tt)))
season <- NULL
remainder <- x - trend
}
return(list(x=x,trend=trend,season=season,remainder=remainder,
transform=transform,lambda=lambda))
}
ご覧のとおり、季節性がある場合はstl()
(これは を使用しますloess
) を使用し、季節性がない場合はペナルティ付き回帰スプラインを使用します。