roll_lag | R Documentation |
Inspired by 'collapse', roll_lag
and roll_diff
operate similarly to
flag
and fdiff
.
roll_lag(x, n = 1L, ...)
## Default S3 method:
roll_lag(x, n = 1L, g = NULL, fill = NULL, ...)
roll_diff(x, n = 1L, ...)
## Default S3 method:
roll_diff(x, n = 1L, g = NULL, fill = NULL, differences = 1L, ...)
diff_(
x,
n = 1L,
differences = 1L,
order = NULL,
run_lengths = NULL,
fill = NULL
)
x |
A vector or data frame. |
n |
Lag. This will be recycled to match the length of x and can be negative. |
... |
Arguments passed onto appropriate method. |
g |
Grouping vector. This can be a vector, data frame or |
fill |
Value to fill the first |
differences |
Number indicating the number of times to recursively apply
the differencing algorithm. If |
order |
Optionally specify an ordering with which to apply the lags/differences. This is useful for example when applying lags chronologically using an unsorted time variable. |
run_lengths |
Optional integer vector of run lengths that defines
the size of each lag run. For example, supplying |
While these may not be as fast the 'collapse' equivalents,
they are adequately fast and efficient.
A key difference between roll_lag
and flag
is that g
does not need
to be sorted for the result to be correct.
Furthermore, a vector of lags can be supplied for a custom rolling lag.
For time-based lags, see time_lag.
roll_diff()
silently returns NA
when there is integer overflow.
Both roll_lag()
and roll_diff()
apply recursively to list elements.
A vector the same length as x
.
library(timeplyr)
x <- 1:10
roll_lag(x) # Lag
roll_lag(x, -1) # Lead
roll_diff(x) # Lag diff
roll_diff(x, -1) # Lead diff
# Using cheapr::lag_sequence()
# Differences lagged at 5, first 5 differences are compared to x[1]
roll_diff(x, cheapr::lag_sequence(length(x), 5, partial = TRUE))
# Like diff() but x/y instead of x-y
quotient <- function(x, n = 1L){
x / roll_lag(x, n)
}
# People often call this a growth rate
# but it's just a percentage difference
# See ?roll_growth_rate for growth rate calculations
quotient(1:10)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.