filterSparse: Filter values of a sparse matrix or vector

View source: R/utils.R

filterSparseR Documentation

Filter values of a sparse matrix or vector

Description

Filters the non-zero values of a sparse matrix or sparse vector object according to a user-provided function (e.g. to take only values above a certain threshold, or only greater than the mean), returning a sparse object with the same dimension as the input, but having only the non-zero values that meet the desired criteria.

Usage

filterSparse(X, fn, ...)

Arguments

X

A sparse matrix or sparse vector.

fn

A function taking as first argument a vector of non-zero values (which will be extracted from 'X') and returning a logical/boolean vector of the same length as the first argument, returning 'TRUE' for values that are to be kept and 'FALSE' for values that are to be discarded.

Alternatively, can pass a logical/boolean vector of the same length as 'X@x'.

If any of the returned values is 'NA', will put a 'NA' value at that position.

...

Extra arguments to pass to 'fn'.

Value

A sparse matrix or sparse vector of the same class as 'X' and with the same dimensions, but having only the non-zero values that meet the condition specificed by 'fn'.

Examples

library(Matrix)
library(MatrixExtra)

### Random sparse matrix
set.seed(1)
X <- rsparsematrix(nrow=20, ncol=10, density=0.3)

### Take only values above 0.5
X_filtered <- filterSparse(X, function(x) x >= 0.5)

### Only elements with absolute values less than 0.3
X_filtered <- filterSparse(X, function(x) abs(x) <= 0.3)

### Only values above the mean (among non-zeros)
X_filtered <- filterSparse(X, function(x) x > mean(x))

MatrixExtra documentation built on May 29, 2024, 2:53 a.m.