Here are two options, including speed checking. The first uses the "shift" function from the "binhf" library:
library(binhf) M <- matrix(1:12,3,4) system.time( for ( t in 1:100000 ) { n <- nrow(M) m <- ncol(M) A <- cbind(M,matrix(NA,n,n-1)) for (i in 1:n) { A[i,] <- shift(A[i,],i-1) } } )
It is shorter but slower:
User System verstrichen 9.64 0.00 9.73 > A [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 4 7 10 NA NA [2,] NA 2 5 8 11 NA [3,] NA NA 3 6 9 12
"basic R" solution:
M <- matrix(1:12,3,4) system.time( for ( t in 1:100000 ) { n <- nrow(M) m <- ncol(M) k <- (0:(n-1))*(m+n)+1 i <- outer(k,1:m,"+")-1 a <- rep(NA,n*(m+n-1)) a[i] <- M A <- matrix(a,n,m+n-1,byrow=TRUE) } )
It is longer but faster:
User System verstrichen 4.09 0.00 4.18 > A [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 4 7 10 NA NA [2,] NA 2 5 8 11 NA [3,] NA NA 3 6 9 12
This is the matrix used for the test:
> M [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12
I repeated the test using a 15 by 20 matrix. The result for the “shift” solution:
User System verstrichen 64.18 0.01 64.66
Again, the "basic R" resolution is faster:
User System verstrichen 10.89 0.00 10.99
Code speed is a question somewhere in the middle:
User System verstrichen 29.44 0.02 29.63
And here is the result for the "rowlide" solution:
User System verstrichen 14.38 0.00 14.48
Finally, the "turn_out" solution:
User System verstrichen 18.95 0.00 19.03