Find the "previous" or "next" values in a vector.
Useful for comparing values behind or ahead of the current values.
lag(x, n = 1L, default = NA)
lead(x, n = 1L, default = NA)
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.
Examples
x <- 1:5
lag(x, 1)
#> [1] NA 1 2 3 4
lead(x, 1)
#> [1] 2 3 4 5 NA
# Also works inside of `mutate()`
df <- tidytable(x = 1:5)
df %>%
mutate(lag_x = lag(x))
#> # A tidytable: 5 × 2
#> x lag_x
#> <int> <int>
#> 1 1 NA
#> 2 2 1
#> 3 3 2
#> 4 4 3
#> 5 5 4