R: Deseasonalizing a time series

r, stl-decomposition, time-series

Solution

Yes, that will work.

Or just use the `seasadj` function in the `forecast` package. However, with the `AirPassengers` data, an additive decomposition such as that given in `stl` is not a good choice. You could take logs first, and then it gives reasonable results.

library(forecast)
library(ggplot2)

decomp <- stl(log(AirPassengers), s.window="periodic")
ap.sa <- exp(seasadj(decomp))
autoplot(cbind(AirPassengers, SeasonallyAdjusted=ap.sa)) +
  xlab("Year") + ylab("Number of passengers (thousands)")

Problem

We can use following code to plot and decompose a time series in R: ``` # Monthly Airline Passenger Numbers 1949-1960 data(AirPassengers) data = data.frame(AirPassengers) data #Transform to time series ts.data1 = ts(data=as.vector(t(data['AirPassengers'])), start = c(1949), end = c(1960), frequency=12) #Plot seasonality, trend plot(stl(ts.data1, "periodic")) plot(ts.data1) decomposed <- stl(ts.data1, s.window="periodic") seasonal <- decomposed$time.series[,1] trend <- decomposed$time.series[,2] remainder <- decomposed$time.series[,3] #Show seasonal effect seasonal ``` Now comes my question: in order to deseasonalize, can I simply type ``` # deseasonalize time sereis ts.data1 <- ts.data1 - seasonal ts.data1 plot(ts.data1) ``` to subtract the seasonal values? I realized that in another dataset, subtracting the seasonal values caused negative values. That's why I thought using a factor or something would be better. Note: I'd prefer not to use the "deseasonalize" package.

Original source