行标准化稀疏矩阵

Row standardize a Sparse Matrix

我有以下稀疏矩阵;-

library(Matrix)
 a <- sparseMatrix(i = c(1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5),
                   j = c(1, 2, 2, 3, 2, 3, 4, 5, 3, 1, 5), x = 1)

我想将行除以它们的行总和,使该矩阵成为以下稀疏矩阵:-

b <- sparseMatrix(i = c(1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5),
                  j = c(1, 2, 2, 3, 2, 3, 4, 5, 3, 1, 5),
                  x = c(0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 1, 0.5, 0.5))

如何在 R 中对稀疏矩阵进行行标准化

您可以将 a 除以行总和。

b <- a/rowSums(a)
b
#5 x 5 sparse Matrix of class "dgCMatrix"
                            
#[1,] 0.5 0.50 .    .    .   
#[2,] .   0.50 0.50 .    .   
#[3,] .   0.25 0.25 0.25 0.25
#[4,] .   .    1.00 .    .   
#[5,] 0.5 .    .    .    0.50