Skip to content

Seamless R and C++ integration for the sparse matrix dgCMatrix class

Notifications You must be signed in to change notification settings

zdebruine/RcppSparse

Folders and files

NameName
Last commit message
Last commit date

Latest commit

d1690c0 · Jul 1, 2022

History

72 Commits
Nov 20, 2021
Jul 1, 2022
Nov 4, 2021
Nov 20, 2021
Nov 25, 2021
Nov 20, 2021
Nov 20, 2021
Nov 4, 2021
Nov 20, 2021

Repository files navigation

RcppSparse

RcppSparse provides a seamless Rcpp object class for R sparse matrix objects. The RcppSparse::Matrix class can directly import Matrix::dgCMatrix-class objects from R without any copying by simply using base Rcpp types (IntegerVector and NumericVector).

The result is a constant, by-reference, zero-copy Rcpp sparse matrix class. In contrast, RcppArmadillo and RcppEigen are deep copies.

Install RcppSparse from CRAN with install.packages("RcppSparse") and then load the header library in your C++ file:

//[[Rcpp::depends(RcppSparse)]]
#include RcppSparse.h // this line before ever including Rcpp.h

Now you're set to roll! Here's a simple program to compute column sums of a sparse matrix:

//[[Rcpp::export]]
Rcpp::NumericVector columnSums(RcppSparse::Matrix& A) {
    Rcpp::NumericVector sums(A.cols());
    for (size_t col = 0; col < A.cols(); ++col)
        for (RcppSparse::Matrix::InnerIterator it(A, col); it; ++it)
            sums(col) += it.value();
    return sums;
}

To use this function from the R end, just make sure you pass a dgCMatrix into the function:

library(Matrix)
A <- rsparsematrix(nrow = 10, ncol = 10, density = 0.1)
class(A) # this is a "dgCMatrix"
columnSums(A)

The idea of a zero-copy sparse matrix class is discussed on the Rcpp gallery.

About

Seamless R and C++ integration for the sparse matrix dgCMatrix class

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published