.BG
.FN apply
.TL
Apply a Function to Sections of an Array
.CS
apply(X, MARGIN, FUN, ...)
.AG X
array.  Missing values (`NA's) are allowed if `FUN' accepts them.
.AG MARGIN
the subscripts over which the function is to be applied.
For example, if `X' is a matrix, 1 indicates rows, and 2 indicates columns.
For a more complex example of the use of `MARGIN', see
the last example below.
In general, a subarray is extracted from `X' for each
combination of the levels of the subscripts named in
`MARGIN'. The function `FUN' is invoked for each of these
subarrays, and the results, if any, concatenated into a new
array. Note that `MARGIN' tells which dimensions of `X'
are retained in the result.
.AG FUN
function (or
character string giving the name of the function) to be
applied to the specified array sections.
The character form is necessary only for functions with
unusual names, e.g., "%*%".
.AG ...
optional, any arguments to `FUN'; they are passed unchanged
to each call of `FUN'.
.RT
If each call to `FUN' returns a vector of length `N',
and `N>1', `apply' returns an
array of dimension
.Cs
c(N,dim(X)[MARGIN])
.Ce
If `N==1' and `MARGIN'
has length > 1, the value is an array of dimension `dim(X)[MARGIN]' ;
otherwise, it is a vector.
.EX
apply(x,2,mean,trim=.25)   #  25% trimmed column means
       # The result is a vector of length `ncol(x)'

apply(x,2,sort)    # sort columns of x

t(apply(x,1,sort))   # transpose result of row sort

apply(z,c(1,3),sum)
.PP
The sorting examples show the difference between
row and column operations when the
results returned by `FUN' are vectors.  The returned value
becomes the
.I first
dimension of the result, hence the transpose
is necessary with row sorts.
.PP
Suppose, in the last example, that `z' is a 4-way
array with dimension vector
(2,3,4,5).  The expression computes the 2 by 4 matrix obtained by
summing over the second and fourth extents of `z' (i.e., `sum' is
called 8 times, each time on 15 values).
.PP
Each section of the input array is passed as the first argument to an
invocation of `FUN'.  It is passed without a keyword modifier, so, by
keywords attached to `argi', it should be possible to make the array
section correspond to any argument to `FUN'.
.br
.ne 3
.SA
Function `lapply' applies a function to each element of a list.
Function `tapply' applies a function to a ragged array, defined by
categories.
.KW iteration
.KW algebra
.KW array
.WR
