Description Usage Arguments Examples
Lead and lag are useful for comparing values offset by a constant (e.g. the previous or next value)
1 2 3 |
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. |
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)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.