Closed hadley closed 4 years ago
vec_lag()
and vec_lead()
seem straightforward-ish from dplyr::lag
and dplyr::lead
library(vctrs)
library(rlang)
vec_lag <- function (x, n = 1L) {
vec_assert(x)
n <- vec_cast(n, integer())
vec_assert(n, size = 1L)
if (n < 0L) {
abort("`n` must be positive.")
}
if (n == 0L) {
return(x)
}
size <- vec_size(x)
n <- pmin(n, size)
new <- vec_init(x, n)
old <- vec_slice(x, seq_len(size - n))
vec_c(new, old)
}
vec_lead <- function (x, n = 1L) {
vec_assert(x)
n <- vec_cast(n, integer())
vec_assert(n, size = 1L)
if (n < 0L) {
abort("`n` must be positive.")
}
if (n == 0L) {
return(x)
}
size <- vec_size(x)
n <- pmin(n, size)
new <- vec_init(x, n)
old <- vec_slice(x, -seq_len(n))
vec_c(old, new)
}
cars <- mtcars[1:3,]
vec_lag(cars, 1)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 NA NA NA NA NA NA NA NA NA NA NA
#> 2 21 6 160 110 3.9 2.620 16.46 0 1 4 4
#> 3 21 6 160 110 3.9 2.875 17.02 0 1 4 4
vec_lag(cars, 2)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 NA NA NA NA NA NA NA NA NA NA NA
#> 2 NA NA NA NA NA NA NA NA NA NA NA
#> 3 21 6 160 110 3.9 2.62 16.46 0 1 4 4
vec_lag(cars, -1)
#> `n` must be positive.
vec_lead(cars, 1)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> 2 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> 3 NA NA NA NA NA NA NA NA NA NA NA
vec_lead(cars, 2)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
#> 2 NA NA NA NA NA NA NA NA NA NA NA
#> 3 NA NA NA NA NA NA NA NA NA NA NA
Created on 2019-10-04 by the reprex package (v0.2.1)
Moved to individual issues
Window functions: lead/lag, rank etc Cumulative: cumany cumall Vectorised: if_else recode case_when near