TO_scipy_sparse: conversion of an R sparse matrix to a scipy sparse matrix

View source: R/nmslib.R

TO_scipy_sparseR Documentation

conversion of an R sparse matrix to a scipy sparse matrix

Description

conversion of an R sparse matrix to a scipy sparse matrix

Usage

TO_scipy_sparse(R_sparse_matrix)

Arguments

R_sparse_matrix

an R sparse matrix. Acceptable input objects are either a dgCMatrix or a dgRMatrix.

Details

This function allows the user to convert either an R dgCMatrix or a dgRMatrix to a scipy sparse matrix (scipy.sparse.csc_matrix or scipy.sparse.csr_matrix). This is useful because the nmslibR package accepts besides an R dense matrix also python sparse matrices as input.

The dgCMatrix class is a class of sparse numeric matrices in the compressed, sparse, column-oriented format. The dgRMatrix class is a class of sparse numeric matrices in the compressed, sparse, column-oriented format.

References

https://stat.ethz.ch/R-manual/R-devel/library/Matrix/html/dgCMatrix-class.html, https://stat.ethz.ch/R-manual/R-devel/library/Matrix/html/dgRMatrix-class.html, https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html#scipy.sparse.csc_matrix

Examples


try({
  if (reticulate::py_available(initialize = FALSE)) {
    if (reticulate::py_module_available("scipy")) {

      if (Sys.info()["sysname"] != 'Darwin') {

        library(nmslibR)


        # 'dgCMatrix' sparse matrix
        #--------------------------

        data = c(1, 0, 2, 0, 0, 3, 4, 5, 6)

        dgcM = Matrix::Matrix(data = data, nrow = 3,

                              ncol = 3, byrow = TRUE,

                              sparse = TRUE)

        print(dim(dgcM))

        res = TO_scipy_sparse(dgcM)

        print(res$shape)


        # 'dgRMatrix' sparse matrix
        #--------------------------

        dgrM = as(dgcM, "RsparseMatrix")

        print(dim(dgrM))

        res_dgr = TO_scipy_sparse(dgrM)

        print(res_dgr$shape)
      }
    }
  }
}, silent=TRUE)

nmslibR documentation built on Feb. 16, 2023, 5:17 p.m.