Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement lag() and lead() #13

Closed
msberends opened this issue May 2, 2020 · 0 comments
Closed

Implement lag() and lead() #13

msberends opened this issue May 2, 2020 · 0 comments
Labels
feature request New feature or request

Comments

@msberends
Copy link
Contributor

msberends commented May 2, 2020

Getting more and more enthusiastic about this package 馃槂

For lag() and lead(), also used often in data wrangling:

lag <- function (x, n = 1L, default = NA, ...) {
  if (length(n) != 1 || !is.numeric(n) || n < 0) {
    stop("n must be a nonnegative integer scalar")
  }
  if (n == 0) {
    return(x)
  }
  xlen <- length(x)
  n <- pmin(n, xlen)
  out <- c(rep(default, n), x[seq_len(xlen - n)])
  attributes(out) <- attributes(x)
  out
}

lead <- function (x, n = 1L, default = NA, ...) {
  if (length(n) != 1 || !is.numeric(n) || n < 0) {
    stop("n must be a nonnegative integer scalar")
  }
  if (n == 0) {
    return(x)
  }
  xlen <- length(x)
  n <- pmin(n, xlen)
  out <- c(x[-seq_len(n)], rep(default, n))
  attributes(out) <- attributes(x)
  out
}

Reprex:

test <- factor(letters[1:10])

lag(test)
#> [1] <NA> a    b    c    d    e    f    g    h    i   
#> Levels: a b c d e f g h i j

lead(test)
#> [1] b    c    d    e    f    g    h    i    j    <NA>
#> Levels: a b c d e f g h i j

identical(dplyr::lag(test), lag(test))
#> [1] TRUE

identical(dplyr::lead(test), lead(test))
#> [1] TRUE
@nathaneastwood nathaneastwood added the feature request New feature or request label May 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants