Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Deseasonalizing a time series

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.

like image 487
Rnaldinho Avatar asked Mar 11 '23 19:03

Rnaldinho


1 Answers

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)")

enter image description here

like image 166
Rob Hyndman Avatar answered Mar 27 '23 05:03

Rob Hyndman