mapSparse: Map values of a sparse matrix/vector

View source: R/utils.R

mapSparseR Documentation

Map values of a sparse matrix/vector

Description

Applies a function to the non-zero values of a sparse object, returning the transformed input with the new non-zero values.

Usage

mapSparse(X, fn, ...)

Arguments

X

A sparse matrix or sparse vector, whose non-zero values will be transformed/mapped according to 'fn'.

fn

A function taking as first argument a vector of non-zero values (which will be extracted from 'X') and returning another vector of the same length as the first argument, which will become the non-zero values of the output.

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

If the results are of a different type than the input (e.g. input is 'lsparseMatrix', but 'fn' returns a numeric vector), the type will be automatically converted to match the type returned by 'fn'.

...

Extra arguments to pass to 'fn'.

Value

A sparse object with the same storage order (T/C/R), dimension, and number of non-zero entries as 'X', but with its non-zero values substituted by the output from 'fn', and the exact class determined by the type returned by 'fn'.

Examples

library(Matrix)
library(MatrixExtra)

set.seed(1)
X <- rsparsematrix(10, 5, .5)
print(mapSparse(X, function(x) abs(x)+1))

MatrixExtra documentation built on Aug. 21, 2023, 1:08 a.m.