File: lead-lag.Rd

package info (click to toggle)
r-cran-dplyr 1.1.4-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,292 kB
  • sloc: cpp: 1,403; sh: 17; makefile: 7
file content (69 lines) | stat: -rw-r--r-- 1,775 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lead-lag.R
\name{lead-lag}
\alias{lead-lag}
\alias{lag}
\alias{lead}
\title{Compute lagged or leading values}
\usage{
lag(x, n = 1L, default = NULL, order_by = NULL, ...)

lead(x, n = 1L, default = NULL, order_by = NULL, ...)
}
\arguments{
\item{x}{A vector}

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

\item{default}{The value used to pad \code{x} back to its original size after the
lag or lead has been applied. The default, \code{NULL}, pads with a missing
value. If supplied, this must be a vector with size 1, which will be cast
to the type of \code{x}.}

\item{order_by}{An optional secondary vector that defines the ordering to use
when applying the lag or lead to \code{x}. If supplied, this must be the same
size as \code{x}.}

\item{...}{Not used.}
}
\value{
A vector with the same type and size as \code{x}.
}
\description{
Find the "previous" (\code{lag()}) or "next" (\code{lead()}) values in a vector. Useful
for comparing values behind of or ahead of the current values.
}
\examples{
lag(1:5)
lead(1:5)

x <- 1:5
tibble(behind = lag(x), x, ahead = lead(x))

# If you want to look more rows behind or ahead, use `n`
lag(1:5, n = 1)
lag(1:5, n = 2)

lead(1:5, n = 1)
lead(1:5, n = 2)

# If you want to define a value to pad with, use `default`
lag(1:5)
lag(1:5, default = 0)

lead(1:5)
lead(1:5, default = 6)

# If the data are not already ordered, use `order_by`
scrambled <- slice_sample(
  tibble(year = 2000:2005, value = (0:5) ^ 2),
  prop = 1
)

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

right <- mutate(scrambled, previous_year_value = lag(value, order_by = year))
arrange(right, year)
}