filterSparse | R Documentation |
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.
filterSparse(X, fn, ...)
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'. |
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'.
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))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.