Apply a function of multiple arguments to cells of a identically structures ragged arrays, that is to each set
of (non-empty) groups of values given by a unique combination of the
levels of certain factors. It is a hybrid of tapply
and mapply
.
mtapply(X, INDEX, FUN = NULL, simplify = TRUE)
a list of atomic objects, typically vectors, all of the same length
list of factors, each of same length as X
. The
elements are coerced to factors by as.factor
.
the function to be applied, or NULL
. In the case of
functions like +
, %*%
, etc., the function name must
be backquoted or quoted. If FUN
is NULL
, tapply
returns a vector which can be used to subscript the multi-way array
mtapply
normally produces.
If FALSE
, tapply
always returns an array
of mode "list"
. If TRUE
(the default), then if
FUN
always returns a scalar, tapply
returns an array
with the mode of the scalar.
If FUN
is not NULL
, it is passed to
match.fun
, and hence it can be a function or a symbol or
character string naming a function.
When FUN
is present, mtapply
calls FUN
for each
set of cells that has any data in it. If FUN
returns a single atomic
value for each such cell (e.g., functions mean
or var
)
and when simplify
is TRUE
, tapply
returns a
multi-way array containing the values, and NA
for the
empty cells. The array has the same number of dimensions as
INDEX
has components; the number of levels in a dimension is
the number of levels (nlevels()
) in the corresponding component
of INDEX
. Note that if the return value has a class (e.g. an
object of class "Date"
) the class is discarded.
If FUN
does not return a single atomic value, tapply
returns an array of mode list
whose components are the
values of the individual calls to FUN
, i.e., the result is a
list with a dim
attribute.
When there is an array answer, its dimnames
are named by
the names of INDEX
and are based on the levels of the grouping
factors (possibly after coercion).
For a list result, the elements corresponding to empty cells are
NULL
.
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
the functions link{tapply}
,
mapply
,
by
and
aggregate
(using tapply
);
apply
,
lapply
with its versions
sapply
and mapply
.
# NOT RUN {
require(Hmisc)
x<-1:10
fc<-rep(c("a","b"),each=5)
wt<-1:10
mtapply(list(x,wt),fc,wtd.mean)
mtapply(list(x,rep(1/10,10)),fc,wtd.mean)
# }
Run the code above in your browser using DataLab