rowsum-methods: rowsum() methods for sparse matrices

rowsum-methodsR Documentation

rowsum() methods for sparse matrices

Description

The SparseArray package provides memory-efficient rowsum() and colsum() methods for SparseMatrix and dgCMatrix objects.

Usage

## S4 method for signature 'SparseMatrix'
rowsum(x, group, reorder=TRUE, ...)

## S4 method for signature 'dgCMatrix'
rowsum(x, group, reorder=TRUE, ...)

## S4 method for signature 'SparseMatrix'
colsum(x, group, reorder=TRUE, ...)

## S4 method for signature 'dgCMatrix'
colsum(x, group, reorder=TRUE, ...)

Arguments

x

A SparseMatrix or dgCMatrix object.

group, reorder

See ?base::rowsum for a description of these arguments.

...

Like the default S3 rowsum() method defined in the base package, the methods documented in this man page support additional argument na.rm, set to FALSE by default. If TRUE, missing values (NA or NaN) are omitted from the calculations.

Value

An ordinary matrix, like the default rowsum() method. See ?base::rowsum for how the matrix returned by the default rowsum() method is obtained.

See Also

  • rowsum in base R.

  • S4Arrays::rowsum in the S4Arrays package for the rowsum() and colsum() S4 generic functions.

  • SparseMatrix objects.

  • dgCMatrix objects implemented in the Matrix package.

Examples

svt0 <- randomSparseMatrix(7e5, 100, density=0.15)
dgcm0 <- as(svt0, "dgCMatrix")
m0 <- as.matrix(svt0)

group <- sample(10, nrow(m0), replace=TRUE)

## Calling rowsum() on the sparse representations is usually faster
## than on the dense representation:
rs1 <- rowsum(m0, group)
rs2 <- rowsum(svt0, group)   # about 3x faster
rs3 <- rowsum(dgcm0, group)  # also about 3x faster

## Sanity checks:
stopifnot(identical(rs1, rs2))
stopifnot(identical(rs1, rs3))

Bioconductor/SparseArray documentation built on Nov. 14, 2024, 6:22 p.m.