% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/back_period.R
\name{back_period}
\alias{back_period}
\title{Back period}
\usage{
back_period(period, product = NULL, match_first = TRUE, offset = 1L)
}
\arguments{
\item{period}{\verb{[factor]} A factor, or something that can be coerced into one,
that
gives the time period for each transaction. The ordering of time periods
follows the levels of \code{period} to agree with
\code{\link[=cut.Date]{cut()}}.}

\item{product}{\verb{[factor]} A factor, or something that can be coerced into
one, that
gives the product identifier for each transaction. The default is to
assume that all transactions are for the same product.}

\item{match_first}{\verb{[logical(1)]} Should products in the first period match
with themselves (the default)?}

\item{offset}{\verb{[integer(1)]} The number of periods to offset. The default
offsets by one period (back period). Setting to \code{nlevels(period)} gives
the the base period.}
}
\value{
A numeric vector of indices giving the position of the the back periods.
}
\description{
Offset a vector prices or quantities by computing the position one (or more)
period backwards for each product.
}
\note{
By definition, there must be at most one transaction for each product
in each time period to determine a back period. If multiple transactions
correspond to a period-product pair, then the back period at a point in
time is always the first position for that product in the previous period.
}
\examples{
prices <- data.frame(
  price = 1:6,
  product = factor(c("a", "b")),
  period = factor(c(1, 1, 2, 2, 3, 3))
)

with(prices, back_period(period, product))

# Make fixed-base price relatives.
with(
  prices,
  price / price[back_period(period, product, offset = nlevels(period))]
)

# Change the base period with relevel().
with(
  prices,
  price / price[
    back_period(relevel(period, "2"), product, offset = nlevels(period))
  ]
)
}
\seealso{
\code{\link[=outliers]{outliers()}} for common methods to detect outliers for price relatives.

\code{rs_pairs} in the \pkg{rsmatrix} package for making sales pairs.
}
