How to create a sparse matrix in R?


A sparse matrix is a type of matrix that has most of the elements equal to zero but there is no restriction for the number of zero elements. As a general criterion the number of non−zero elements are expected to be equal to the number of rows or number of columns. To create a sparse matrix in R, we can use sparseMatrix function of Matrix package.

Example1

 Live Demo

Loading Matrix package and creating a sparse 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"

Output

[1,] . 3 . . .
[2,] . 1 3 2 .
[3,] . . . . .
[4,] . 2 . . .
[5,] . . . . 5
[6,] . . . . .
[7,] . . . . .
[8,] . . . 0 .

Example2

 Live Demo

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"

Output

[1,] . 5 . . . . .
[2,] . . . 3 . . .
[3,] . . . . 0 . .
[4,] . 3 . . . . 3
[5,] . . . . . . .
[6,] . . . 1 . . .
[7,] . 2 . . . . .
[8,] . . 3 . . . .
[9,] . . . . 2 . .
[10,] . . 1 . . . .

Example3

 Live Demo

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"

Output

[1,] . 7 . . . . .
[2,] . . . 8 . . .
[3,] . . . . 7 . .
[4,] . 4 . . . . 4
[5,] . . . . . . .
[6,] . . . 6 . . .
[7,] . 4 . . . . .
[8,] . . 6 . . . .
[9,] . . . . 7 . .
[10,] . . 4 . . . .

Example4

 Live Demo

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"

Output

[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 . . . . . . .

Example5

 Live Demo

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"

Output

[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 . . . . . . .

Updated on: 08-Feb-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements