Converting matrix to sparse matrix

As we know, matrices in R programming language are the objects or collections of elements arranged in a two-dimensional layout. We can construct a matrix in R using the matrix() function.

The first step we are going to do is to install the Matrix package using install.packages(“Matrix”) and then load the package using the library function in R. Next, we are going to construct our matrix using the matrix() function provided by the Matrix package. After the matrix has been generated, create an equivalent sparse matrix using as().

Syntax : 

sparsematrix <- as(BaseMatrix, “sparseMatrix”)

Parameters :

  • sparsematrix : This is our sample sparse matrix which is to be converted from our base matrix.
  • BaseMatrix : This is our sample R matrix.
  • “sparseMatrix” : It is the category specified inside the as() function to convert the base R matrix to sparse format.

Example: Converting matrix to sparse matrix in R

R




# loading the Matrix package
library(Matrix)
  
# Constructing a base R matrix 
set.seed(0)
nrows <- 6L
ncols <- 8L
values <- sample(x = c(0,1,2,3), prob = c(0.6,0.2,0.4,0.8), 
                 size = nrows*ncols, replace = TRUE)
  
BaseMatrix <- matrix(values, nrow = nrows)
BaseMatrix
  
# For converting base matrix to sparse matrix
sparsematrix <- as(BaseMatrix, "sparseMatrix")
sparsematrix


Output :

Convert matrix or dataframe to sparse Matrix in R

Sparse matrices are in column-oriented format and they contain mostly null values. The elements in the sparse matrix which are non-null are arranged in ascending order. In this article, we will convert the matrix and dataframe to a sparse matrix in R programming language.

Similar Reads

Converting matrix to sparse matrix

As we know, matrices in R programming language are the objects or collections of elements arranged in a two-dimensional layout. We can construct a matrix in R using the matrix() function....

Converting a dataframe to sparse matrix

...