O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

To filter time series data, follow these steps:

  1. Read the data. The file has fictitious weekly sales data for some product:
> s <- read.csv("ts-example.csv") 
  1. Create the filtering vector. We assume a seven-period filter:
> n <- 7 
> wts <- rep(1/n, n) 
  1. Compute the symmetrically filtered values (three past values, one current value, and three future values) and one-sided values (one current and six past values):
> s.filter1 <- filter(s$sales, filter = wts, sides = 2) 
> s.filter2 <- filter(s$sales, filter = wts, sides = 1) 
  1. Plot the filtered values:
> plot(s$sales, type = "l") 
> lines(s.filter1, col = "blue", lwd = 3) 
> lines(s.filter2, col = "red", lwd = 3) 

The plotted filtered values appear as follows:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required