Time Series Decomposition in R (2024)

Data Science Institute Tutor Team

In a previous tutorial, we discussed the basics of time series and time series analysis. We looked at how to convert data into time series data and analyse this in R. In this tutorial, we'll go into more depth and look at time series decomposition.

We’ll firstly recap the components of time series and then discuss the moving average concept. After that we’ll focus on two time series decompositions – a simple method based on moving averages and the local regression method.

You can download the data files for this tutorial here

Components of Time Series

We know that there are four time series components, out of which trend and seasonality are the main components. We can assume two models for time series – the additive model and the multiplicative model. When we assume the additive model, the data at any period t, that is ‘Yt’, is the addition of the trend ‘Tt’, seasonal ‘St’ and error ‘Rt’ components at period t.

Alternatively, in a multiplication model, we assume that Yt is the multiplication of different components Tt, St and Rt. When the magnitude of seasonal fluctuations or the variation around a trend cycle does not vary with the level of time series, the additive model is more appropriate than the multiplicative model.

Time Series Decomposition in R (2)

Yt : Time series value at period t

St : Seasonal component at period t

Tt : Trend-cycle component at period t

Rt : Remainder (or irregular or error) component at period t

Alternatively, a multiplicative model would be written as:

Time Series Decomposition in R (3)

Understanding Moving Averages

In time series analysis, the moving average method is a common approach for estimating trends in time series. So let's understand how moving averages are calculated. Moving averages are averages calculated for consecutive data from overlapping subgroups of fixed length. Moving averages smoothen the time series by filtering out random fluctuations. The period of moving average depends on the type of data. For non-seasonal data, a shorter length, typically a 3 period or a 5-period moving average, is considered.

For seasonal data, the length equals the number of observations in a season, 12 for monthly data, 4 for quarterly data, etc.

While calculating a moving average of period 3, the first 2 moving averages are not calculated. The moving average for day 3 is the average of values at day 1,2 and 3. The moving average for day 4 is the average of values at day 2,3 and 4. Similarly, for a period 5, the first four moving averages are not calculated.Time Series Decomposition in R (4)

Time Series Decomposition – Simple Method

Let's now try to understand the first technique of time series decomposition. Decomposition is a statistical method that deconstructs a time series. The three basics steps to decompose a time series using the simple method are:


    1) Estimating the trend
    2) Eliminating the trend
    3) Estimating Seasonality

To find the trend, we obtain moving averages covering one season. We then eliminate the trend component from the original time series by calculating Yt minus Tt, where Tt is the trend value. Thirdly, to estimate the seasonal component for a given time period, we average the de-trended values for that time period. We then adjust these seasonal indexes to ensure that they add to zero. The remainder component is calculated by subtracting the estimated seasonal and trend-cycle components.

Time Series Decomposition in R (5)

Let’s consider an example. Suppose we have monthly time series data for three years 2014, 2015 and 2016. First, calculate the moving average. We consider 13 values for capturing the trend in the yearly data – that is – we consider the previous 6 months, the following 6 months, and the current month to calculate moving average for the current month. This gives us the trend component. After doing that, we remove the trend component Tt from the original time series Yt. Finally, the seasonal index for July is the average of all the de-trended July values in the data, that is the average de-trended for July 2014, July 2015 and July 2016. Note that this moving averages approach is slightly different from what we discussed earlier as it uses pre and post-data values for a given period moving average.Time Series Decomposition in R (6)
Time Series Decomposition in R (7)
Time Series Decomposition in R (8)

Case Study

Let’s consider a case study of monthly sales data for three years from 2013 to 2015. The objective of the study is to apply decomposition methods and analyse each component of the time series separately. We have 36 records with year, month, and sales as the variables of the study.

Time Series Decomposition in R (9)

Data Snapshot

Here is a snapshot of the data. We have three columns representing three variables Year and Month are time variables, whereas Sales is our time series of interest.Time Series Decomposition in R (10)

Time Series Decomposition in R – Simple Method

First import our data using the read.csv function. As discussed in the previous tutorial, we’ll use the ‘ts’ function in R to convert a variable from a data frame to a time series object. We specify the x-axis scale, that is the year and month in our data, as the start and end argument. frequency=12 tells R that we have monthly data. Once we set our data frame to a time series object, we perform a classical seasonal decomposition through moving average by using the decompose function. We then plot the decomposed data using the plot function in R.

# Time Series Decomposition

salesdata<-read.csv("Sales Data for 3 Years.csv",header=TRUE)

salesseries<-ts(salesdata$Sales,start=c(2013,1), end=c(2015,12), frequency=12)

ts() converts a column from a data frame to a simple time series object.

start= and end= arguments specify the x-axis scale. (Year and month in this case).

frequency=12 tells that we have monthly data

decomp<-decompose(salesseries)

plot(decomp)

decompose() performs classical seasonal decomposition through moving averages.

plot() of decompose object gives a 4-level visual representation

R uses the default additive time series model to decompose the data. To use the multiplicative model, we specify type equals to multiplicative in the decompose function. We don’t calculate the trend with the first and last few values. The seasonal component repeats from year to year.

Here we see a very nice clean visualization showing our original time series, trend, seasonal and random components.

#Output
Time Series Decomposition in R (11)

We can view each component of the time series separately by using the object name and the ($) operator. Since the trend has not been estimated for the first and last values, we can see na’s in the output. This will be reflected in the random component as well.

#Analysing the decompose() object. Each component can be separately viewed by using the $ operator.

Time Series Decomposition in R (12)

By subtracting the seasonal component from the original time series we can obtain a seasonally adjusted time series as shown in this plot here.

# Doing Seasonal Adjustment

seasadj <- salesseries - decomp$seasonal

plot(seasadj)

# Output

Time Series Decomposition in R (13)

Time Series Decomposition – Local

Regression Method (LOESS)

Let's now look at the second technique of time series decomposition called the local regression method abbreviated as LOESS. This is a non-parametric generalisation of ordinary least squares regression. The fitting technique does not require a prior specification of the relationship between the dependent and independent variables. The seasonal and trend decomposition using the LOESS method abbreviated as STL works by iterating through the smoothing of the seasonal and trend components. STL is a procedure for regular time series, so that the design points of the smoothing operation are equally spaced.

Time Series Decomposition in R – LOESS Method

In R, the stl function is used to carry out decomposition by LOESS method. The s.window specifies the seasonal window by using either a character string ‘periodic’ or the span (in lags) of the LOESS window for the seasonal extraction. The t.window specifies the trend window for trend extraction, which should be odd number or kept as the default. Here, we have not specified t.window so R will use the default value. We will extract the seasonal window of the data by specifying s.window equals to periodic and then plot this decomposed time series using the plot function.

#Local Regression Method for Seasonal Decomposition.

decomp<-stl(salesseries,s.window="periodic")

plot(decomp)

stl() in used to carry out decomposition by loess method.

t.window= specifies trend window. It takes the span (in lags) of the loess window for trend extraction, which should be odd. If NULL, the default, nextodd(ceiling((1.5*period) / (1-(1.5/s.window)))) is taken.

s.window= specifies seasonal window. It uses either the character string “periodic” or the span (in lags) of the loess window for seasonal extraction.

The data shows the trend and seasonality components of the time series. The trend values are estimated for all periods.

# Output
Time Series Decomposition in R (14)

Quick Recap

Here is a quick recap what we have covered - we learnt how to decompose a time series using the simple and the LOESS method. The loess method is used for estimating non-linear relationships. The decompose function carries out simple seasonal decomposition whereas the stl function is used for doing the LOESS decomposition.

Time Series Decomposition in R (15)

DATA SCIENCE INSTITUTE

Phone: 01 442 9653

Whatsapp: 089 973 5641

email info@datascienceinstitute.net

  • About the Data Science Institute
  • Accreditation and Recognition
  • Partners
  • Our people
  • Privacy
  • 13 Adelaide Road,Dublin,D02 P950Ireland

PROFESSIONAL CREDENTIALS

  • Our Certifications
  • Certified Professional Data Analyst CPDA
  • Certified Professional Data Scientist CPDS
  • Fellow of the Data Science Institute FDSI

DATA SCIENCE COURSES

  • Professional Certificate in Data Science
  • Postgraduate Diploma in Data Science
  • Masters in Data Science
Time Series Decomposition in R (2024)

FAQs

How to do time series decomposition in R? ›

Time Series Decomposition Using R: Step by Step
  1. STEP 1: Import the data. ...
  2. STEP 2: Detect the Trend. ...
  3. STEP 3: Detrend the Time Series to get the preliminary seasonality. ...
  4. STEP 4: Average the Seasonality to get better accuracy. ...
  5. STEP 5: Random Noise = Time series – Seasonality – Trend.
Aug 21, 2019

What is STL time series decomposition in R? ›

In R the stl() function performs decomposition of a time series into seasonal, trend and irregular components using Loess. The function requires the s. window argument, which is either the character string "periodic" or the span (in lags), an odd number, of the loess window for seasonal extraction.

How to use ts() in r? ›

The ts() function will convert a numeric vector into an R time series object. The format is ts(vector, start=, end=, frequency=) where start and end are the times of the first and last observation and frequency is the number of observations per unit time (1=annual, 4=quartly, 12=monthly, etc.).

What is the difference between Detrending and time series decomposition? ›

While working with a data series that exhibits a clear trend and before processing the data further it is needed to remove the trend from the data. This is called detrending . Time series data is often thought of as being comprised of several components: a long-term trend, seasonal variation, and irregular variations.

How do you visualize time series data in R? ›

The R programming language provides a strong of tools in the ggplot2 package to visualize data. We can use the geom_line() function to visualize the time-series data using a line plot.

How do you Deseasonalize a time series? ›

Given S ^ t , the deseasonalized series is calculated by subtracting (or dividing by) the estimated seasonal component, depending on the assumed decomposition. For an additive decomposition, the deseasonalized series is given by d t = y t − S ^ t .

How do you do the decomposition method? ›

To decompose a number, break apart the number into parts. The number 9 can be decomposed into 9 and 0, 1 and 8, 2 and 7, 3 and 6, or 4 and 5.

What is classical decomposition of time series? ›

The classic decomposition calculates the trend component by smoothing the original time series with a seasonality / 2xseasonality moving average filter (2xseasonality if seasonality is even, seasonality if it is uneven).

How does decompose work in R? ›

decompose() performs classical seasonal decomposition through moving averages. R uses the default additive time series model to decompose the data. To use the multiplicative model, we specify type equals to multiplicative in the decompose function. We don't calculate the trend with the first and last few values.

What is the difference between STL and classical decomposition? ›

STL Decomposition

The main advantage of the STL method (vs. the classical method) is the ability to control the smoothing period of both the trend and seasonal component. That becomes a super useful series that has a multiplicative seasonality.

What is time series analysis in R? ›

in R time series analysis this function is mostly used to learn and forecast the behavior of an asset in business for a while. For example, sales analysis of a company, inventory analysis, price analysis of a particular stock or market, population analysis, etc. where, data – represents the data vector.

What is the R package for time series? ›

The R package 'timeSeries' provides a time series class and tools for creation, import, manipulation, statistical and financial computations on time series. Package timeSeries is part of the Rmetrics suite of R packages and is developed on R-forge at timeSeries. The root of Rmetrics is at R-forge.

How to check if data is time series in R? ›

When you use datasets from others, such as those included in an R package, you can check whether they are ts objects using the is. ts() command. The result of the test is either TRUE when the data is of the ts class, or FALSE if it is not.

How to differ a time series in R? ›

In R we can use the diff() function for differencing a time series, which requires 3 arguments: x (the data), lag (the lag at which to difference), and differences (the order of differencing; d in Equation (4.7)).

How to convert data into time series data in R? ›

To convert a data frame to a time series in R, the data frame needs to contain a date or datetime column that will be used as the time index. Once the data frame is loaded, the xts package can be used to convert it to a time series object by using the as. xts() function.

How to conduct time series analysis in R? ›

Implementing Time Series Analysis in R
  1. Step 1: Loading the Dataset. # Load the dataset data("AirPassengers") # Print the first few rows print(head(AirPassengers)) ...
  2. Step 2: Checking the Structure of the Dataset. ...
  3. Step 3: Plotting the Dataset. ...
  4. Step 4: Decomposing the Time Series Data. ...
  5. Step 5: Forecasting Future Data.
Sep 21, 2023

How do you Deseasonalize time series data? ›

To deseasonalize our data, we just need to subtract the seasonal component from the original data. Notice that the plot seems more jagged than the original one. Now it doesn't have a strong seasonal component, but we can see the trend more clearly.

How to stationarize time series data in R? ›

There are three commonly used technique to make a time series stationary:
  1. Detrending : Here, we simply remove the trend component from the time series. ...
  2. Differencing : This is the commonly used technique to remove non-stationarity. ...
  3. Seasonality: Seasonality can easily be incorporated in the ARIMA model directly.

Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 5377

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.