tgs_matrix_tapply: For each matrix row apply a function over a ragged array

View source: R/matrix.R

tgs_matrix_tapplyR Documentation

For each matrix row apply a function over a ragged array

Description

For each matrix row apply a function to each cell of a ragged array, that is to each (non-empty) group of values given by a unique combination of the levels of certain factors.

Usage

tgs_matrix_tapply(x, index, fun, ...)

Arguments

x

a matrix or a sparse matrix of 'dgCMatrix' type

index

a 'list' of one or more 'factor's, each of same length as the number of columns in 'x'. The elements are coerced to factors by 'as.factor'.

fun

the function to be applied

...

optional arguments to 'fun'

Details

'tgs_matrix_tapply(x, index, fun)' is essentialy an efficient implementation of 'apply(mat, 1, function(x) tapply(x, index, fun))'.

Value

A matrix of length(index) X nrow(x) size. Each [i,j] element represents the result of applying 'fun' to x[i,which(index==levels(index)[j])].
Note that the return value is a dense matrix even when x is sparse.

Examples


# Note: all the available CPU cores might be used

set.seed(seed = 1)
nr <- 6
nc <- 10
mat <- matrix(sample(c(rep(0, 6), 1:3), nr * nc, replace = TRUE), nrow = nr, ncol = nc)
index <- factor(rep_len(1:3, ncol(mat)), levels = 0:5)
r1 <- apply(mat, 1, function(x) tapply(x, index, sum))
r2 <- tgs_matrix_tapply(mat, index, sum)





tgstat documentation built on July 9, 2023, 6:06 p.m.