如何在 R 中创建稀疏矩阵?
稀疏矩阵是一种大部分元素等于零的矩阵,但对零元素的数量没有限制。作为一般标准,非零元素的数量应等于行数或列数。为了在 R 中创建稀疏矩阵,我们可以使用 Matrix 包的 sparseMatrix 函数。
示例 1
加载 Matrix 包并创建稀疏矩阵 -
library(Matrix) i<−c(1,5,2,4,2,2,8);j<−c(2,5,3,2,4,2,4);x<−rpois(7,2) M1<−sparseMatrix(i,j,x=x) M1 8 x 5 sparse Matrix of class "dgCMatrix"
输出
[1,] . 3 . . . [2,] . 1 3 2 . [3,] . . . . . [4,] . 2 . . . [5,] . . . . 5 [6,] . . . . . [7,] . . . . . [8,] . . . 0 .
示例 2
i<−c(1,3,8,4,2,7,6,9,1,4,10);j<−c(2,5,3,2,4,2,4,5,2,7,3);x<−rpois(11,2) M2<−sparseMatrix(i,j,x=x) M2 10 x 7 sparse Matrix of class "dgCMatrix"
输出
[1,] . 5 . . . . . [2,] . . . 3 . . . [3,] . . . . 0 . . [4,] . 3 . . . . 3 [5,] . . . . . . . [6,] . . . 1 . . . [7,] . 2 . . . . . [8,] . . 3 . . . . [9,] . . . . 2 . . [10,] . . 1 . . . .
示例 3
i<−c(1,3,8,4,2,7,6,9,1,4,10);j<−c(2,5,3,2,4,2,4,5,2,7,3);x<−rpois(11,5) M3<−sparseMatrix(i,j,x=x) M3 10 x 7 sparse Matrix of class "dgCMatrix"
输出
[1,] . 7 . . . . . [2,] . . . 8 . . . [3,] . . . . 7 . . [4,] . 4 . . . . 4 [5,] . . . . . . . [6,] . . . 6 . . . [7,] . 4 . . . . . [8,] . . 6 . . . . [9,] . . . . 7 . . [10,] . . 4 . . . .
示例 4
i<−c(1,3,8,4,2,7,6,9,1,4,10,5,11,2,12);j<−c(2,5,3,8,6,2,4,2,4,5,2,7,3,2,1);x<−rpois(15,5) M4<−sparseMatrix(i,j,x=x) M4 12 x 8 sparse Matrix of class "dgCMatrix"
输出
[1,] . 4 . 1 . . . . [2,] . 4 . . . 5 . . [3,] . . . . 6 . . . [4,] . . . . 4 . . 1 [5,] . . . . . . 5 . [6,] . . . 5 . . . . [7,] . 2 . . . . . . [8,] . . 9 . . . . . [9,] . 1 . . . . . . [10,] . 3 . . . . . . [11,] . . 0 . . . . . [12,] 5 . . . . . . .
示例 5
i<−c(1,3,8,4,2,7,6,9,1,4,10,5,11,2,12);j<−c(2,5,3,8,6,2,4,2,4,5,2,7,3,2,1);x<−round(rnorm(15),2) M5<−sparseMatrix(i,j,x=x) M5 12 x 8 sparse Matrix of class "dgCMatrix"
输出
[1,] . −1.04 . −0.79 . . . . [2,] . 0.40 . . . 2.1 . . [3,] . . . . −1.37 . . . [4,] . . . . 0.18 . . −0.68 [5,] . . . . . . −0.21 . [6,] . . . −1.49 . . . . [7,] . 0.05 . . . . . . [8,] . . −1.86 . . . . . [9,] . −0.49 . . . . . . [10,] . 0.66 . . . . . . [11,] . . −1.25 . . . . . [12,] −0.02 . . . . . . .
广告