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 |







