Lagging Variables in R

r, time-series

Solution

You can achieve this using the built-in `embed()` function, where its second 'dimension' argument is equivalent to what you've called 'lag':

x <- c(NA,NA,1,2,3,4)
embed(x,3)

## returns
     [,1] [,2] [,3]
[1,]    1   NA   NA
[2,]    2    1   NA
[3,]    3    2    1
[4,]    4    3    2

`embed()` was discussed in a previous answer by Joshua Reich. (Note that I prepended x with NAs to replicate your desired output).

It's not particularly well-named but it is quite useful and powerful for operations involving sliding windows, such as rolling sums and moving averages.

Problem

What is the most efficient way to make a matrix of lagged variables in R for an arbitrary variable (i.e. not a regular time series) For example: Input: ``` x <- c(1,2,3,4) ``` 2 lags, output: ``` [1,NA, NA] [2, 1, NA] [3, 2, 1] [4, 3, 2] ```

Original source

Related problems