.BG
.VE $Header: /usr3/s/current/s/.help/RCS/apply,v 1.2 83/12/30 19:24:02 rab Exp $
.FN apply
.TL
apply: Apply a Function to Sections of an Array
.CS
apply(a, margin, fun, arg1, arg2, ...)
.PP
.AG a
array.  Missing values (NAs) are allowed if `fun' accepts them.
.AG margin
the subscripts over which the function is to be applied.
For example, if `a' 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 `a' 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' is also the dimensions of `a'
which are retained in the result.
.AG fun
character string giving the name of the function to be
applied to the specified array sections.
.AG argi
optional, any arguments to `fun'; they are passed unchanged.
.RT
array whose dimensions are defined by `margin'.  If the
result of each application of `fun' has a length that is
greater than 1, this length will be the new first dimension
of the result.  If `margin' only specifies one dimension to
be saved, and `fun' returns results of length 1, a vector
will be returned.
.PP
The system macros `?row(a,fun,...)' and `?col(a,fun,...)'
apply a function over rows and columns of a
matrix.
.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 FIRST dimension of the result, hence the transpose
is necessary with row sorts.
.PP
In the last example, `z' is a 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'.
.PP
The function must return the same number of values (possibly 0) each
time it is invoked on an array section.
.PP
System infix operators such as "+" can also be passed as functions.
.PP
Function `sapply' can be used to apply over all components of structures.
Function `tapply' is useful for ragged arrays.
The language looping construct `for' is more general than `apply', but is
less efficient computationally.
.KW multi*
.KW apply*
.KW algebra
.WR
