\HeaderA{by}{Apply a Function to a Data Frame split by Factors}{by}
\methaliasA{by.data.frame}{by}{by.data.frame}
\methaliasA{by.default}{by}{by.default}
\aliasA{print.by}{by}{print.by}
\keyword{iteration}{by}
\keyword{category}{by}
\begin{Description}\relax
Function \code{by} is an object-oriented wrapper for
\code{\LinkA{tapply}{tapply}} applied to data frames.
\end{Description}
\begin{Usage}
\begin{verbatim}
by(data, INDICES, FUN, ..., simplify = TRUE)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{data}] an \R{} object, normally a data frame, possibly a matrix.
\item[\code{INDICES}] a factor or a list of factors, each of length
\code{nrow(data)}.
\item[\code{FUN}] a function to be applied to data frame subsets of \code{data}.
\item[\code{...}] further arguments to \code{FUN}.
\item[\code{simplify}] logical: see \code{\LinkA{tapply}{tapply}}.
\end{ldescription}
\end{Arguments}
\begin{Details}\relax
A data frame is split by row into data frames
subsetted by the values of one or more factors, and function
\code{FUN} is applied to each subset in turn.

Object \code{data} will be coerced to a data frame by the default
method, \emph{but} if this results in a 1-column data frame, the
objects passed to \code{FUN} are dropped to a subsets of that column.
(This was the long-term behaviour, but only documented since \R{} 2.7.0.)
\end{Details}
\begin{Value}
An object of class \code{"by"}, giving the results for each subset.
This is always a list if \code{simplify} is false, otherwise a list or
array (see \code{\LinkA{tapply}{tapply}}).
\end{Value}
\begin{SeeAlso}\relax
\code{\LinkA{tapply}{tapply}}
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
require(stats)
attach(warpbreaks)
by(warpbreaks[, 1:2], tension, summary)
by(warpbreaks[, 1], list(wool = wool, tension = tension), summary)
by(warpbreaks, tension, function(x) lm(breaks ~ wool, data = x))

## now suppose we want to extract the coefficients by group
tmp <- by(warpbreaks, tension, function(x) lm(breaks ~ wool, data = x))
sapply(tmp, coef)

detach("warpbreaks")
\end{ExampleCode}
\end{Examples}

