一种更快(矢量化)的方法,用于创建具有预定长度的1和0的滑动序列

Jas*_*lns 6 for-loop r vectorization

我有以下功能,但我觉得有一个更快(矢量化或可能是一个包或内置?)的方式来写这个?

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
Run Code Online (Sandbox Code Playgroud)

Rol*_*and 7

创建稀疏带状矩阵:

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,] . . . . . | |
Run Code Online (Sandbox Code Playgroud)

如果需要密集的数字矩阵,可以使用+as.matrix(...)最后一步.