Skip to contents

Find a shifted version of a matrix, adjusting the time base backward (lagged) or forward (leading) by a specified number of observations for each column.

Usage

lagmatrix(x, lag)

Arguments

x

A matrix or multivariate time series.

lag

A vector of lags (positive values) or leads (negative values) with a length equal to the number of columns of x.

Value

A matrix with the same class and size as x.

Examples

x <- matrix(rnorm(20), nrow = 5, ncol = 4)

# Create lags of a matrix
lagmatrix(x, c(0, 1, 2, 3))
#>            [,1]       [,2]        [,3]       [,4]
#> [1,] -0.2214920         NA          NA         NA
#> [2,] -0.5327543  1.8372813          NA         NA
#> [3,] -0.2527562 -0.5168990 -0.08607230         NA
#> [4,]  0.5297525  0.4238086 -0.02822395 -0.6379241
#> [5,] -0.3590142 -1.4433878 -1.12939293  0.7739003
#> attr(,"class")
#> [1] "matrix" "array" 

# Create leads of a matrix
lagmatrix(x, c(0, -1, -2, -3))
#>            [,1]       [,2]       [,3]       [,4]
#> [1,] -0.2214920 -0.5168990 -1.1293929  0.4635259
#> [2,] -0.5327543  0.4238086 -0.7501841 -1.3311060
#> [3,] -0.2527562 -1.4433878 -0.3077862         NA
#> [4,]  0.5297525 -1.5429724         NA         NA
#> [5,] -0.3590142         NA         NA         NA
#> attr(,"class")
#> [1] "matrix" "array"