% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/period.apply.R
\name{period.apply}
\alias{period.apply}
\title{Apply Function Over Specified Interval}
\usage{
period.apply(x, INDEX, FUN, ...)
}
\arguments{
\item{x}{The data that \code{FUN} will be applied to.}

\item{INDEX}{A numeric vector of index breakpoint locations. The vector
should begin with 0 and end with \code{nrow(x)}.}

\item{FUN}{A function to apply to each interval in \code{x}.}

\item{\dots}{Additional arguments for \code{FUN}.}
}
\value{
An object with \code{length(INDEX) - 1} observations, assuming \code{INDEX}
starts with 0 and ends with \code{nrow(x)}.
}
\description{
Apply a specified function to data over intervals specified by \code{INDEX}. The
intervals are defined as the observations from \code{INDEX[k]+1} to \code{INDEX[k+1]},
for \code{k = 1:(length(INDEX)-1)}.
}
\details{
Similar to the rest of the apply family, \code{period.apply()} calculates the
specified function's value over a subset of data. The primary difference is
that \code{period.apply()} applies the function to non-overlapping intervals of a
vector or matrix.

Useful for applying functions over an entire data object by any
non-overlapping intervals. For example, when \code{INDEX} is the result of a
call to \code{endpoints()}.

\code{period.apply()} checks that \code{INDEX} is sorted, unique, starts with 0, and
ends with \code{nrow(x)}. All those conditions are true of vectors returned by
\code{endpoints()}.
}
\note{
When \code{FUN = mean} the results will contain one column for every
column in the input, which is different from other math functions (e.g.
\code{median}, \code{sum}, \code{prod}, \code{sd}, etc.).

\code{FUN = mean} works by column because the default method \code{stats::mean}
previously worked by column for matrices and data.frames. R Core changed the
behavior of \code{mean} to always return one column in order to be consistent
with the other math functions. This broke some \pkg{xts} dependencies and
\code{mean.xts()} was created to maintain the original behavior.

Using \code{FUN = mean} will print a message that describes this inconsistency.
To avoid the message and confusion, use \code{FUN = colMeans} to calculate means
by column and use \code{FUN = function(x) mean} to calculate one mean for all the
data. Set \code{options(xts.message.period.apply.mean = FALSE)} to suppress this
message.
}
\examples{

zoo.data <- zoo(rnorm(31)+10,as.Date(13514:13744,origin="1970-01-01"))
ep <- endpoints(zoo.data,'weeks')
period.apply(zoo.data, INDEX=ep, FUN=function(x) colMeans(x))
period.apply(zoo.data, INDEX=ep, FUN=colMeans)                  #same

period.apply(letters,c(0,5,7,26), paste0)

}
\seealso{
\code{\link[=endpoints]{endpoints()}} \code{\link[=apply.monthly]{apply.monthly()}}
}
\author{
Jeffrey A. Ryan, Joshua M. Ulrich
}
\keyword{utilities}
