Filtering time series data

This recipe shows how we can use the filter function from the stats package to compute moving averages.

Getting ready

If you have not already done so, download the data files for this chapter and ensure that they are available in your R working directory.

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")
  2. Create the filtering vector. We assume a seven-period filter:
    > n <- 7
    > wts <- rep(1/n, n)
  3. 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) ...

Get R: Recipes for Analysis, Visualization and Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.