Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lag a matrix in R

Tags:

r

matrix

lag

I want to know the command in R to lag a matrix. I have defined x as:

> (x <- matrix(1:50, 10, 5))
       [,1] [,2] [,3] [,4] [,5]
 [1,]    1   11   21   31   41
 [2,]    2   12   22   32   42
 [3,]    3   13   23   33   43
 [4,]    4   14   24   34   44
 [5,]    5   15   25   35   45
 [6,]    6   16   26   36   46
 [7,]    7   17   27   37   47
 [8,]    8   18   28   38   48
 [9,]    9   19   29   39   49
[10,]   10   20   30   40   50

I want create l.x:

       [,1] [,2] [,3] [,4] [,5]
 [1,]    NA  NA   NA   NA   NA
 [2,]    1   11   21   31   41
 [3,]    2   12   22   32   42
 [4,]    3   13   23   33   43
 [5,]    4   14   24   34   44
 [6,]    5   15   25   35   45
 [7,]    6   16   26   36   46
 [8,]    7   17   27   37   47
 [9,]    8   18   28   38   48
[10,]    9   19   29   39   49
like image 818
Matteo Guidarini Avatar asked Dec 11 '22 16:12

Matteo Guidarini


1 Answers

lag will coerce your object to a time-series (ts class to be specific) and only shifts the time index. It does not change the underlying data.

You need to manually lag the matrix yourself by adding rows of NA at the beginning and removing the same number of rows at the end. Here's an example of a function that does just that:

lagmatrix <- function(x, k) {
  # ensure 'x' is a matrix
  stopifnot(is.matrix(x))
  if (k == 0)
    return(x)
  na <- matrix(NA, nrow=abs(k), ncol=ncol(x))
  if (k > 0) {
    nr <- nrow(x)
    # prepend NA and remove rows from end
    rbind(na, x[-((nr-k):nr),])
  } else {
    # append NA and remove rows from beginning
    rbind(x[-1:k,], na)
  }
}

Or you can use a lag function that does what you expect. For example, xts::lag.xts.

> xts::lag.xts(x)
      [,1] [,2] [,3] [,4] [,5]
 [1,]   NA   NA   NA   NA   NA
 [2,]    1   11   21   31   41
 [3,]    2   12   22   32   42
 [4,]    3   13   23   33   43
 [5,]    4   14   24   34   44
 [6,]    5   15   25   35   45
 [7,]    6   16   26   36   46
 [8,]    7   17   27   37   47
 [9,]    8   18   28   38   48
[10,]    9   19   29   39   49
> is.matrix(xts::lag.xts(x))
[1] TRUE
like image 114
Joshua Ulrich Avatar answered Jan 06 '23 19:01

Joshua Ulrich