https://github.com/hadley/dplyr
Raw File
Tip revision: e2a2a00cb5054175d9e4489a43088c2dff35525d authored by hadley on 22 June 2017, 14:06:26 UTC
Update site
Tip revision: e2a2a00
lead-lag.Rd
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lead-lag.R
\name{lead-lag}
\alias{lead-lag}
\alias{lead}
\alias{lag}
\title{Lead and lag.}
\usage{
lead(x, n = 1L, default = NA, order_by = NULL, ...)

lag(x, n = 1L, default = NA, order_by = NULL, ...)
}
\arguments{
\item{x}{a vector of values}

\item{n}{a postive integer of length 1, giving the number of positions to
lead or lag by}

\item{default}{value used for non-existant rows. Defaults to \code{NA}.}

\item{order_by}{override the default ordering to use another vector}

\item{...}{Needed for compatibility with lag generic.}
}
\description{
Find the "next" or "previous" values in a vector. Useful for comparing values
ahead of or behind the current values.
}
\examples{
lead(1:10, 1)
lead(1:10, 2)

lag(1:10, 1)
lead(1:10, 1)

x <- runif(5)
cbind(ahead = lead(x), x, behind = lag(x))

# Use order_by if data not already ordered
df <- data.frame(year = 2000:2005, value = (0:5) ^ 2)
scrambled <- df[sample(nrow(df)), ]

wrong <- mutate(scrambled, prev = lag(value))
arrange(wrong, year)

right <- mutate(scrambled, prev = lag(value, order_by = year))
arrange(right, year)
}
back to top