Find the "next" or "previous" values in a vector. Useful for comparing values ahead of or behind the current values.
lead(x, n = 1L, default = NA, order_by = NULL, ...) lag(x, n = 1L, default = NA, order_by = NULL, ...)
| x | a vector of values |
|---|---|
| n | a postive integer of length 1, giving the number of positions to lead or lag by |
| default | value used for non-existant rows. Defaults to |
| order_by | override the default ordering to use another vector |
| ... | Needed for compatibility with lag generic. |
lead(1:10, 1)#> [1] 2 3 4 5 6 7 8 9 10 NAlead(1:10, 2)#> [1] 3 4 5 6 7 8 9 10 NA NAlag(1:10, 1)#> [1] NA 1 2 3 4 5 6 7 8 9lead(1:10, 1)#> [1] 2 3 4 5 6 7 8 9 10 NAx <- runif(5) cbind(ahead = lead(x), x, behind = lag(x))#> ahead x behind #> [1,] 0.50314610 0.36004240 NA #> [2,] 0.07463363 0.50314610 0.36004240 #> [3,] 0.96979189 0.07463363 0.50314610 #> [4,] 0.64850131 0.96979189 0.07463363 #> [5,] NA 0.64850131 0.96979189# 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)#> year value prev #> 1 2000 0 16 #> 2 2001 1 9 #> 3 2002 4 25 #> 4 2003 9 4 #> 5 2004 16 1 #> 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