Hmisc (version 3.0-12)

mApply: 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 if attributes and storage modes of the original variables are saved by calling subsAttr. subsAttr saves attributes that are commonly preserved across row subsetting (i.e., it does not save dim, dimnames, or names attributes).

Usage

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

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.

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.

concept

  • apply for matrix
  • apply for vector

See Also

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

Examples

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

Run the code above in your browser using DataCamp Workspace