I have the following function which works, but I feel like there's a faster (either vectorized or perhaps a package or built-in?) way to write this?
create_seq <- function(n, len) {
mat <- matrix(nrow = length(0:(n-len)), ncol = n)
for(i in 0:(n-len)) {
mat[i + 1, ] <- c(rep(0L, i), rep(1L, len), rep(0L, n - (len + i)))
}
return(mat)
}
create_seq(10, 3)
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#> [1,] 1 1 1 0 0 0 0 0 0 0
#> [2,] 0 1 1 1 0 0 0 0 0 0
#> [3,] 0 0 1 1 1 0 0 0 0 0
#> [4,] 0 0 0 1 1 1 0 0 0 0
#> [5,] 0 0 0 0 1 1 1 0 0 0
#> [6,] 0 0 0 0 0 1 1 1 0 0
#> [7,] 0 0 0 0 0 0 1 1 1 0
#> [8,] 0 0 0 0 0 0 0 1 1 1
create_seq(10, 5)
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#> [1,] 1 1 1 1 1 0 0 0 0 0
#> [2,] 0 1 1 1 1 1 0 0 0 0
#> [3,] 0 0 1 1 1 1 1 0 0 0
#> [4,] 0 0 0 1 1 1 1 1 0 0
#> [5,] 0 0 0 0 1 1 1 1 1 0
#> [6,] 0 0 0 0 0 1 1 1 1 1
create_seq(7, 2)
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#> [1,] 1 1 0 0 0 0 0
#> [2,] 0 1 1 0 0 0 0
#> [3,] 0 0 1 1 0 0 0
#> [4,] 0 0 0 1 1 0 0
#> [5,] 0 0 0 0 1 1 0
#> [6,] 0 0 0 0 0 1 1
Create a sparse banded matrix:
library(Matrix)
create_seq_sparse <- function(n, len) {
bandSparse(m = n, n = n - len + 1L, k = seq_len(len) - 1L)
}
create_seq_sparse(10, 3)
# 8 x 10 sparse Matrix of class "ngCMatrix"
#
# [1,] | | | . . . . . . .
# [2,] . | | | . . . . . .
# [3,] . . | | | . . . . .
# [4,] . . . | | | . . . .
# [5,] . . . . | | | . . .
# [6,] . . . . . | | | . .
# [7,] . . . . . . | | | .
# [8,] . . . . . . . | | |
create_seq_sparse(7, 2)
#6 x 7 sparse Matrix of class "ngCMatrix"
#
#[1,] | | . . . . .
#[2,] . | | . . . .
#[3,] . . | | . . .
#[4,] . . . | | . .
#[5,] . . . . | | .
#[6,] . . . . . | |
If you need a dense numeric matrix, you can use +as.matrix(...)
as the last step.
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