goal
I want to use a long vector of numbers to create a matrix where each column is a sequential offset (lag or start) of the original vector. If n is the maximum displacement, the matrix will have dimensions [length(vector), n * 2 + 1] (because we want displacements in both directions and turn on the displacement 0, that is, the Original vector).
Example
To illustrate, consider the following vector:
test <- c(2, 8, 1, 10, 7, 5, 9, 3, 4, 6) [1] 2 8 1 10 7 5 9 3 4 6
Expected Result
Now we create value offsets, say for n == 3 :
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] NA NA NA 2 8 1 10 [2,] NA NA 2 8 1 10 7 [3,] NA 2 8 1 10 7 5 [4,] 2 8 1 10 7 5 9 [5,] 8 1 10 7 5 9 3 [6,] 1 10 7 5 9 3 4 [7,] 10 7 5 9 3 4 6 [8,] 7 5 9 3 4 6 NA [9,] 5 9 3 4 6 NA NA [10,] 9 3 4 6 NA NA NA
I am looking for an effective solution. data.table or tidyverse solutions are more than welcome.
Returning only rows that do not have NA (i.e. rows 4 through 7) is also fine.
Current solution
lags <- lapply(3:1, function(x) dplyr::lag(test, x)) leads <- lapply(1:3, function(x) dplyr::lead(test, x)) l <- c(lags, test, leads) matrix(unlist(l), nrow = length(test))