Extracting Seasonality and Trend from Data: Decomposition Using R

December 1, 2015 19 Comments math


Time series decomposition works by splitting a time series into three components: seasonality, trends and random fluctiation. To show how this works, we will study the decompose( ) and STL( ) functions in the R language.

Understanding Decomposition

Decompose One Time Series into Multiple Series

Time series decomposition is a mathematical procedure which transforms a time series into multiple different time series. The original time series is often split into 3 component series:

  • Seasonal: Patterns that repeat with a fixed period of time. For example, a website might receive more visits during weekends; this would produce data with a seasonality of 7 days.
  • Trend: The underlying trend of the metrics. A website increasing in popularity should show a general trend that goes up.
  • Random: Also call “noise”, “irregular” or “remainder,” this is the residuals of the original time series after the seasonal and trend series are removed.

Additive or Multiplicative Decomposition?

To achieve successful decomposition, it is important to choose between the additive and multiplicative models, which requires analyzing the series. For example, does the magnitude of the seasonality increase when the time series increases?

additive-modelAustralian beer production – The seasonal variation looks constant; it doesn’t change when the time series value increases. We should use the additive model.

multiplicative-modelAirline Passenger Numbers – As the time series increases in magnitude, the seasonal variation increases as well. Here we should use the multiplicative model.

Time series = Seasonal + Trend + Random

Time series = Trend * Seasonal *Random

The decomposition formula varies a little based on the model.

Step-by-Step: Time Series Decomposition

We’ll study the decompose( ) function in R. As a decomposition function, it takes a time series as a parameter and decomposes it into seasonal, trend and random time series. We’ll reproduce step-by-step the decompose( ) function in R to understand how it works. Since there are variations between the two models, we’ll use two examples: Australian beer production (additive) and airline passenger numbers (multiplicative).

Step 1: Import the Data


As mentioned previously, a good example of additive time series is beer production. As the metric values increase, the seasonality stays relatively constant.


Monthly airline passenger figures are a good example of a multiplicative time series. The more passengers there are, the more seasonality is observed.



Step 2: Detect the Trend

To detect the underlying trend, we smoothe the time series using the “centred moving average“. To perform the decomposition, it is vital to use a moving window of the exact size of the seasonality. Therefore, to decompose a time series we need to know the seasonality period: weekly, monthly, etc… If you don’t know this figure, you can detect the seasonality using a Fourier transform.


Australian beer production clearly follows annual seasonality. As it is recorded quarterly, there are 4 data points recorded per year, and we use a moving average window of 4.


The process here is the same as for the additive model. Airline passenger number seasonality also looks annual. However, it is recorded monthly, so we choose a moving average window of 12.



Step 3: Detrend the Time Series

Removing the previously calculated trend from the time series will result into a new time series that clearly exposes seasonality.





Step 4: Average the Seasonality

From the detrended time series, it’s easy to compute the average seasonality. We add the seasonality together and divide by the seasonality period. Technically speaking, to average together the time series we feed the time series into a matrix. Then, we transform the matrix so each column contains elements of the same period (same day, same month, same quarter, etc…). Finally, we compute the mean of each column. Here is how to do it in R:


Quarterly seasonality: we use a matrix of 4 rows. The average seasonality is repeated 16 times to create the graphic to be compared later (see below)


Monthly seasonality: we use a matrix of 12 rows.
The average seasonality is repeated 12 times to create the graphic we will compare later (see below)



Step 5: Examining Remaining Random Noise

The previous steps have already extracted most of the data from the original time series, leaving behind only “random” noise.


The additive formula is “Time series = Seasonal + Trend + Random”, which means “Random = Time series – Seasonal – Trend”


The multiplicative formula is “Time series = Seasonal * Trend * Random”, which means “Random = Time series / (Trend * Seasonal)”



Step 6: Reconstruct the Original Signal

The decomposed time series can logically be recomposed using the model formula to reproduce the original signal. Some data points will be missing at the beginning and the end of the reconstructed time series, due to the moving average windows which must consume some data before producing average data points.


The additive formula is “Time series = Seasonal + Trend + Random”, which means “Random = Time series – Seasonal – Trend”


The multiplicative formula is “Time series = Seasonal * Trend * Random”, which means “Random = Time series / (Trend * Seasonal)”



DECOMPOSE( ) and STL(): Time Series Decomposition in R

To make life easier, some R packages provides decomposition with a single line of code. As expected, our step-by-step decomposition provides the same results as the DECOMPOSE( ) and STL( ) functions (see the graphs).


The only requirement: seasonality is quarterly (frequency = 4)

Using the DECOMPOSE( ) function:


The only requirement: seasonality is monthly (frequency = 12)



Now using the STL( ) function:



Decomposition is often used to remove the seasonal effect from a time series. It provides a cleaner way to understand trends. For instance, lower ice cream sales during winter don’t necessarily mean a company is performing poorly. To know whether or not this is the case, we need to remove the seasonality from the time series. Here, at Anomaly.io we detect anomalies, and we use seasonally adjusted time series to do so. We also use the random (also call remainder) time series from the decomposed time series to detect anomalies and outliers.

Monitor & detect anomalies with Anomaly.io

  • PaoloRocca

    Nice post.. very well explained!! Thanks

  • Jenice Tom

    Great substance and content, but please proofread.

  • Aleksandras Urbonas

    Can I say ‘wow, this looks professional!’?
    Well thought of, and the layout is amazing.
    I wonder what your topic of interest is now that you have mastered time series :)

  • Jithin Sam Varghese

    Thank you! This was very helpful.

  • http://www.tombush.co.uk/ Tom Bush

    Thanks for this, really helpful. Just curious though — is there a reason you didn’t use stl() on the AirPassengers dataset?

  • Milan Jain

    Very nice article! Can you please suggest what to do when size of each cycle varies i.e. goes from large to small cycles?

  • Elise Gelder

    Does anybody know how to include labels on the x-axis after decomposition. I want the dates to count in months.. It does not work the way it is performed in ‘normal’ plots..

  • Rajesh Pazhyannur

    This is very useful. I have used STL but do appreciate the breakdown. if you have two seasonal periods (say 24 hours, weekly), how would
    you compute the trend. Is it something like this ? compute the moving average with 24 hours, remove the 24 hour average from the series, and then compute a moving average with 7 days.

  • Sacha khoury

    Hello, thanks for this useful forum.
    I was just wondering how do we evalutate if “centred moving average“ model is the best model to fit our time-series before decomposing it?

  • Iman Fatehi

    I want to use this method for my precipitation time series but the remained random noise from my time serie are almost negative values, how can I configure that to consider only x>=0 values?

  • http://arhiuch.ru Владимир Заляжных

    Abnormal values in http://arhiuch.ru

  • nkabouche

    could someone tell me how to choose the “order” “frequency” in “ma” and “ts” functions

  • Alexy Flemming1

    Very brilliant explanation that sum up everything in a little while. A “must” exercise, acc. to me.

  • Atinesh Si

    Thank You for such a beautiful post, exactly that’s what I was looking for.

  • Zach Estela

    Great tutorial!

  • ajare oloruntoba

    Hi everyone, please how can we estimate cyclical out of the model, assuming our interest it to faction out cyclical components of which we already know trend,seasonal from original observations.

  • ajare oloruntoba

    How can i separate random into cyclical and irregular components using R

help with term papers