A faster (vectorized) way to create a sliding sequence of 1s and 0s with a predetermined length

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.


A vectorized base R variant of your function:

create_seq <- function(n, len){
  x <- c(rep(1, len), rep(0, (n - len + 1)))
  y <- rep(x, ceiling(((n - len + 1) * n)/length(x)))
  matrix(y[1:((n - len + 1) * n)], nrow = n - len + 1, ncol = n, byrow = T)
}

This could be shortened to:

create_seq <- function(n, len){
  matrix(rep(c(rep(1, len), rep(0, (n-len+1)))
             , ceiling(((n-len+1)*n)/(n + 1)))[1:((n-len+1)*n)], 
         nrow = n - len + 1, ncol = n, byrow = T)
}

> create_seq(7, 4)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    1    1    1    0    0    0
[2,]    0    1    1    1    1    0    0
[3,]    0    0    1    1    1    1    0
[4,]    0    0    0    1    1    1    1
> create_seq(5, 2)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    0    0
[2,]    0    1    1    0    0
[3,]    0    0    1    1    0
[4,]    0    0    0    1    1