在 R 中用 sapply 填充稀疏矩阵

Fill sparse matrix with sapply in R

假设 X 是一个大型稀疏矩阵,其中每一行只有一个不为零的条目。我有一个向量 pos,其中包含此非零元素所在的列的位置。为了填充矩阵,以下循环起作用:

for (row in 1:nrow(X)) {
    X[row, pos[row]] <- 1
}

有没有没有循环的方法,也许使用 sapply

您可以看看 Matrix 中的 sparseMatrix 函数:

> library(Matrix)
> (pos = sample(1:7))
[1] 5 1 6 4 7 2 3
> sparseMatrix(1:7, pos)
7 x 7 sparse Matrix of class "ngCMatrix"

[1,] . . . . | . .
[2,] | . . . . . .
[3,] . . . . . | .
[4,] . . . | . . .
[5,] . . . . . . |
[6,] . | . . . . .
[7,] . . | . . . .

Matrix 包中的函数需要一些时间来使用,但它们在处理稀疏矩阵时提供了很多好处。