如何在R中创建稀疏矩阵?
矩阵" title="稀疏矩阵">稀疏矩阵是一种矩阵,其大多数元素等于零,但对零元素的数量没有限制。作为一般标准,非零元素的数量应等于行数或列数。要在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 . . . . . . .
以上是 如何在R中创建稀疏矩阵? 的全部内容, 来源链接: utcz.com/z/357391.html