I never understood the lag function, instead I would use the lag from the quantmod package:
> # library(quantmod) > apply(B, 2, Lag) [,1] [,2] [1,] NA NA [2,] 2 1 [3,] 4 5
If you want (or need) to lag behind the matrix without ts attributes, one way can use apply and lag from the quantmod package, but if you do not want to install the package for only one function, then you can write your own function, the idea would be:
lag.matrix <- function(x, k=1){ N <- ncol(B) l <- matrix(embed(x,k+1)[, -c(1:(k*N))], ncol=N) NAs <- matrix(rep(NA, k*N), ncol=N) rbind(NAs, l) } > lag.matrix(B, k=1) [,1] [,2] [1,] NA NA [2,] 2 1 [3,] 4 5 > lag.matrix(B, k=2) [,1] [,2] [1,] NA NA [2,] NA NA [3,] 2 1
Another solution can be posted as a comment from @GSee, which uses lag as you wish.
> lag(xts(B, .POSIXct(0)+0:(nrow(B)-1))) [,1] [,2] 1970-01-01 01:00:00 NA NA 1970-01-01 01:00:01 2 1 1970-01-01 01:00:02 4 5