mApply: Apply a Function to Rows of a Matrix or Vector

View source: R/mApply.s

mApplyR Documentation

Apply a Function to Rows of a Matrix or Vector


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 ( 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.


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



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


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


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


optional arguments to 'FUN'.


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


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


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.


Frank Harrell
Department of Biostatistics
Vanderbilt University

See Also

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


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

harrelfe/Hmisc documentation built on May 19, 2024, 4:13 a.m.