Skip to contents

Compute a lagged version of the input data with multiple lags at once

Usage

lag_multiple(x, k = 1, name = NULL)

Arguments

x

A vector, single column matrix, or univariate time series. Can also be a multi-column matrix if k is length 1.

k

(Optional) An integer vector containing a number of lags. Defaults to 1

name

(Optional) A name to be used in the lagged data.frame. Defaults to the name of the variable passed to x. If that is not possible, name will default to "X".

Value

Returns a data.frame of the lagged variable. The number of rows is the same as the length of the input vector. The number of columns is the number of lags to be used. Each column retains the name of the original variable and includes the number of lags used for that column. If x is a multi-column matrix, returns a matrix of the same number of columns with no names.

Examples

# Creating dummy data
set.seed(1)
x <- rnorm(10)
# for lags 1-5
lag_multiple(x, 1:5)
#>          x_l1       x_l2       x_l3       x_l4       x_l5
#> 1   0.1836433 -0.8356286  1.5952808  0.3295078 -0.8204684
#> 2  -0.8356286  1.5952808  0.3295078 -0.8204684  0.4874291
#> 3   1.5952808  0.3295078 -0.8204684  0.4874291  0.7383247
#> 4   0.3295078 -0.8204684  0.4874291  0.7383247  0.5757814
#> 5  -0.8204684  0.4874291  0.7383247  0.5757814 -0.3053884
#> 6   0.4874291  0.7383247  0.5757814 -0.3053884         NA
#> 7   0.7383247  0.5757814 -0.3053884         NA         NA
#> 8   0.5757814 -0.3053884         NA         NA         NA
#> 9  -0.3053884         NA         NA         NA         NA
#> 10         NA         NA         NA         NA         NA

# 1 lag with a matrix of dummy data
lag_multiple(matrix(1:100, 10, 10), 1)
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#>  [1,]    2   12   22   32   42   52   62   72   82    92
#>  [2,]    3   13   23   33   43   53   63   73   83    93
#>  [3,]    4   14   24   34   44   54   64   74   84    94
#>  [4,]    5   15   25   35   45   55   65   75   85    95
#>  [5,]    6   16   26   36   46   56   66   76   86    96
#>  [6,]    7   17   27   37   47   57   67   77   87    97
#>  [7,]    8   18   28   38   48   58   68   78   88    98
#>  [8,]    9   19   29   39   49   59   69   79   89    99
#>  [9,]   10   20   30   40   50   60   70   80   90   100
#> [10,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA