How to create an off diagonal / moving window matrix with R?
> offdiag(3, 4, 6)
1 1 1 0 0 0
0 1 1 1 0 0
0 0 1 1 1 0
0 0 0 1 1 1 
I suggest creating a sparse logical matrix:
library(Matrix)
X <- bandSparse(n = 4, m = 6, k = seq_len(3) - 1L)
X
#4 x 6 sparse Matrix of class "ngCMatrix"
#
#[1,] | | | . . .
#[2,] . | | | . .
#[3,] . . | | | .
#[4,] . . . | | |
If you need a dense integer matrix:
+as.matrix(X)
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    1    1    1    0    0    0
#[2,]    0    1    1    1    0    0
#[3,]    0    0    1    1    1    0
#[4,]    0    0    0    1    1    1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With