mApply {Hmisc}R Documentation

Apply a Function to Rows of a Matrix or Vector

Description

mApply is like tapply except that the first argument can be a matrix or a vector, and the output is cleaned up if simplify=TRUE. It uses code adapted from Tony Plate (tplate@blackmesacapital.com) to operate on grouped submatrices.

As mApply can be much faster than using by, it is often worth the trouble of converting a data frame to a numeric matrix for processing by mApply. asNumericMatrix will do this, and matrix2dataFrame will convert a numeric matrix back into a data frame.

Usage

mApply(X, INDEX, FUN, ..., simplify=TRUE, keepmatrix=FALSE)

Arguments

X

a vector or matrix capable of being operated on by the function specified as the FUN argument

INDEX

list of factors, each of same number of rows as 'X' has.

FUN

the function to be applied. In the case of functions like '+', '

...

optional arguments to 'FUN'.

simplify

set to 'FALSE' to suppress simplification of the result in to an array, matrix, etc.

keepmatrix

set to TRUE to keep result as a matrix even if simplify is TRUE, in the case of only one stratum

Value

For mApply, the returned value is a vector, matrix, or list. If FUN returns more than one number, the result is an array if simplify=TRUE and is a list otherwise. If a matrix is returned, its rows correspond to unique combinations of INDEX. If INDEX is a list with more than one vector, FUN returns more than one number, and simplify=FALSE, the returned value is a list that is an array with the first dimension corresponding to the last vector in INDEX, the second dimension corresponding to the next to last vector in INDEX, etc., and the elements of the list-array correspond to the values computed by FUN. In this situation the returned value is a regular array if simplify=TRUE. The order of dimensions is as previously but the additional (last) dimension corresponds to values computed by FUN.

Author(s)

Frank Harrell
Department of Biostatistics
Vanderbilt University
fh@fharrell.com

See Also

asNumericMatrix, matrix2dataFrame, tapply, sapply, lapply, mapply, by.

Examples

require(datasets, TRUE)
a <- mApply(iris[,-5], iris$Species, mean)

[Package Hmisc version 5.1-3 Index]