Calculate lags using the diff() function in R

When it comes to doing time series analysis, often times it is necessary to calculate lags for a specific variable. To do this in R, we use the diff() function.

1. Create matrix

For the purposes of this example, we create a matrix with price data for the column names, along with years as our row names:
 
pricedata <- matrix(c(102, 90, 84, 130, 45), ncol=1)
colnames(pricedata) <- c('Price')
rownames(pricedata) <- c('2012', '2013', '2014', '2015', '2016')
pricedata.table <- as.table(pricedata)
pricedata.table

 

Price
2012 102
2013 90
2014 84
2015 130
2016 45

 

2. Lag = 1

diff(pricedata.table,1)

Price
2013 -12
2014 -6
2015 46
2016 -85

 

3. Lag = 2

diff(pricedata.table,2)

Price
2014 -18
2015 40
2016 -39

 

4. Differences = 2

diff(pricedata.table,differences=2)

Price
2014 6
2015 52
2016 131

 

Michael Grogan
Michael Grogan is a data science consultant, with a profound passion for statistics and programming. He regularly utilises statistical programming languages such as Python, R and SQL to analyse a wide range of datasets, with the goal of exploring in depth the tools and methods used across the ever expanding field of data science and business analytics.
Michael Grogan on sabtwitterMichael Grogan on sablinkedinMichael Grogan on sabgoogleMichael Grogan on sabgithubMichael Grogan on sabemail
Subscribe to my mailing list, and receive my free e-book; "How To Use Regression Modelling To Analyse Financial Markets".
Subscribe to my mailing list, and receive my free e-book; "How To Use Regression Modelling To Analyse Financial Markets".
Never display this again