\Header{apply}{Apply Functions Over Array Margins}
\keyword{iteration}{apply}
\keyword{array}{apply}
\begin{Usage}
\begin{verbatim}
apply(x, MARGIN, FUN, ...)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\texttt{x}] the array to be used.
\item[\texttt{MARGIN}] a vector giving the subscripts which the function will
be applied over.
\texttt{1} indicates rows, \texttt{2} indicates columns,
\texttt{c(1,2)} indicates rows and columns.
\item[\texttt{FUN}] the function to be applied.
In the case of functions like \texttt{+}, \texttt{\%*\%}, etc., the
function name must be quoted.
\item[\texttt{...}] optional arguments to \texttt{FUN}.
\end{ldescription}
\end{Arguments}
\begin{Value}
If each call to \texttt{FUN} returns a vector of length \texttt{n}, then
\texttt{apply} returns an array of dimension \texttt{c(n,dim(x)[MARGIN])}
if \texttt{n > 1}.  If \texttt{n} equals \texttt{1}, \texttt{apply} returns a
vector if \texttt{MARGIN} has length 1 and an array of dimension
\texttt{dim(x)[MARGIN]} otherwise.

If the calls to \texttt{FUN} return vectors of different lengths,
\texttt{apply} returns a list of length \texttt{dim(x)[MARGIN]}.\end{Value}
\begin{SeeAlso}
\texttt{\Link{lapply}}, \texttt{\Link{tapply}}, \texttt{\Link{sweep}}.\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8] 
apply(x, 2, mean, trim = .2)
col.sums <- apply(x, 2, sum)
row.sums <- apply(x, 1, sum)
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums)))

all( apply(x,2, is.vector)) # TRUE [was not in R <= 0.63.2]

## Sort the columns of a matrix
apply(x, 2, sort)

##- function with extra args:
cave <- function(x, c1,c2) c(mean(x[c1]),mean(x[c2]))
apply(x,1, cave,  c1="x1", c2=c("x1","x2"))

ma <- matrix(c(1:4, 1, 6:8), nr = 2)
ma
apply(ma, 1, table)  #--> a list of length 2
apply(ma, 1, quantile)# 5 x n matrix with rownames

all(dim(ma) == dim(apply(ma, 1:2, sum)))## apply BUG [R <= 0.63.0]


## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8] 
apply(x, 2, mean, trim = .2)
col.sums <- apply(x, 2, sum)
row.sums <- apply(x, 1, sum)
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums)))

all( apply(x,2, is.vector)) # TRUE [was not in R <= 0.63.2]

## Sort the columns of a matrix
apply(x, 2, sort)

##- function with extra args:
cave <- function(x, c1,c2) c(mean(x[c1]),mean(x[c2]))
apply(x,1, cave,  c1="x1", c2=c("x1","x2"))

ma <- matrix(c(1:4, 1, 6:8), nr = 2)
ma
apply(ma, 1, table)  #--> a list of length 2
apply(ma, 1, quantile)# 5 x n matrix with rownames

all(dim(ma) == dim(apply(ma, 1:2, sum)))## apply BUG [R <= 0.63.0]



\end{ExampleCode}
\end{Examples}

