Open In App

How to Convert Sparse Matrix to Dense Matrix in R?

Improve
Improve
Like Article
Like
Save
Share
Report

R is a programming language used for performing statistical computation and graphical purposes. It is currently supported and backed by the R Core Team and the R Foundation for Statistical Computing. For data analysis and the creation of statistical software, R Programming Language is used by statisticians, bioinformaticians, and data miners. The programming language R is one of the most popular ones for data mining. 

In this article, we are going to see how we can read and convert a sparse matrix to a dense matrix in R.

Sparse Matrix and Dense Matrix

A sparse matrix is any matrix in which the majority of its elements are zero-valued while a dense matrix is just the opposite, i.e., the one in which the majority of elements are non-zero-valued.

The following is a spares matrix:
[[0, 0, 0, 1],
 [7, 0, 0, 0]]
 
While, below is a dense matrix:
[[1, 9, 0, 2],
 [8, 3, 5, 4]]

Matrix Package

We are going to take the help of the Matrix package to do so. The matrix package helps us to perform matrix operations in R. Let us start by installing the package. You can install using the following command:

install.packages("Matrix")

To convert a sparse matrix to a dense matrix, we are going to use the as.matrix() method. It takes data.table object and converts it into a matrix.

Syntax:

as.matrix(x, rownames=NULL, rownames.value=NULL)

Parameters:

  • x: The data.table object.
  • rownames: The column name or number to use as the rownames in the result. It is optional.
  • rownames.value: The values to be used as rownames in the resultant matrix. It is optional.

Example 1: In this example, I have a 6 x 7 sparse matrix with 4 non-zero entries, which I have converted into a dense matrix using the as.matrix() method.

R




library(Matrix)
i <- c(1, 4, 5, 6)
j <- c(2, 7, 3, 1)
x <- c(8, 1, 9, 2)
sm <- sparseMatrix(i, j, x = x)
print(sm)
dm <- as.matrix(sm)
dm


Output:

How to Convert Sparse Matrix to Dense Matrix in R?

 

Example 2: In this example, I have a 7 x 8 sparse matrix with 6 non-zero entries, which I have converted into a dense matrix using the as.matrix() method. I have used the rpois method to generate random numbers.

R




library(Matrix)
i <- c(1, 5, 2, 3, 7, 2)
j <- c(8, 4, 2, 1, 6, 1)
x <- rpois(6, 3)
sm <- sparseMatrix(i, j, x = x)
print(sm)
dm <- as.matrix(sm)
dm


Output:

How to Convert Sparse Matrix to Dense Matrix in R?

 



Last Updated : 23 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads