Learn R Programming

tgstat (version 2.3.14)

tgs_matrix_tapply: 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'

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])].

Details

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

Examples

Run this code
# NOT RUN {
# 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)
# }
# NOT RUN {
# }

Run the code above in your browser using DataLab