mapSparse: Map values of a sparse matrix/vector

Description Usage Arguments Value Examples

View source: R/utils.R

Description

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

Usage

1
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

1
2
3
4
5
6
library(Matrix)
library(MatrixExtra)

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

MatrixExtra documentation built on Sept. 26, 2021, 9:06 a.m.