lead-lag: Compute lagged or leading values

Description Usage Arguments Examples

Description

Find the "previous" (lag()) or "next" (lead()) values in a vector. Useful for comparing values behind of or ahead of the current values.

Usage

1
2
3
lag(x, n = 1L, default = NA, order_by = NULL, ...)

lead(x, n = 1L, default = NA, order_by = NULL, ...)

Arguments

x

Vector of values

n

Positive integer of length 1, giving the number of positions to lead or lag by

default

Value used for non-existent rows. Defaults to NA.

order_by

Override the default ordering to use another vector or column

...

Needed for compatibility with lag generic.

Examples

 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
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 for non-existing rows, use `default`
lag(1:5)
lag(1:5, default = 0)

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

# If 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)

Example output

Attaching package:dplyrThe following objects are masked frompackage:stats:

    filter, lag

The following objects are masked frompackage:base:

    intersect, setdiff, setequal, union

[1] NA  1  2  3  4
[1]  2  3  4  5 NA
# A tibble: 5 x 3
  behind     x ahead
   <int> <int> <int>
1     NA     1     2
2      1     2     3
3      2     3     4
4      3     4     5
5      4     5    NA
[1] NA  1  2  3  4
[1] NA NA  1  2  3
[1]  2  3  4  5 NA
[1]  3  4  5 NA NA
[1] NA  1  2  3  4
[1] 0 1 2 3 4
[1]  2  3  4  5 NA
[1] 2 3 4 5 6
# A tibble: 6 x 3
   year value previous_year_value
  <int> <dbl>               <dbl>
1  2000     0                  25
2  2001     1                   9
3  2002     4                  NA
4  2003     9                   4
5  2004    16                   1
6  2005    25                  16
# A tibble: 6 x 3
   year value previous_year_value
  <int> <dbl>               <dbl>
1  2000     0                  NA
2  2001     1                   0
3  2002     4                   1
4  2003     9                   4
5  2004    16                   9
6  2005    25                  16

dplyr documentation built on June 19, 2021, 1:07 a.m.