lead-lag: Lead and lag.

Description Usage Arguments Examples

Description

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

Usage

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

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

Arguments

x

a vector of values

n

a 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

...

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

Example output

Attaching package: 'dplyr'

The following objects are masked from 'package:stats':

    filter, lag

The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union

 [1]  2  3  4  5  6  7  8  9 10 NA
 [1]  3  4  5  6  7  8  9 10 NA NA
 [1] NA  1  2  3  4  5  6  7  8  9
 [1]  2  3  4  5  6  7  8  9 10 NA
         ahead         x    behind
[1,] 0.5950860 0.6828442        NA
[2,] 0.1095983 0.5950860 0.6828442
[3,] 0.1277737 0.1095983 0.5950860
[4,] 0.5502419 0.1277737 0.1095983
[5,]        NA 0.5502419 0.1277737
  year value prev
1 2000     0    1
2 2001     1    9
3 2002     4   16
4 2003     9    4
5 2004    16   25
6 2005    25   NA
  year value prev
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 July 4, 2019, 5:08 p.m.