Monday, April 4, 2016

Lag and Lead Functions in R

lag <- function(x, n = 1L) {
  xlen <- length(x)
  c(rep(NA, n), x[seq_len(xlen - n)])
}

lead <- function(x, n = 1L) {
  xlen <- length(x)
  c( x[-1*seq_len(xlen - n)],rep(NA, n))
}

No comments:

Post a Comment