Skip to content

Instantly share code, notes, and snippets.

@mbadros
Created January 10, 2018 19:32
Show Gist options
  • Select an option

  • Save mbadros/51b99f28ab7e87b9cd51ad4fd55e914f to your computer and use it in GitHub Desktop.

Select an option

Save mbadros/51b99f28ab7e87b9cd51ad4fd55e914f to your computer and use it in GitHub Desktop.
The function takes as input the vector x and a specified integer lag, and shifts the input series by that amount. NA’s are added to either the beginning or the end (depending on the sign of lag) to pad the shifted vector to be the same length as the input. Note that lag is defined so that a positive lag shifts x “to the right”, i.e. moves values…
# R Function to Shift Vectors
# http://clarkrichards.org/r/timeseries/2016/02/09/a-function-to-shift-vectors/
#
shift <- function(x, lag) {
n <- length(x)
xnew <- rep(NA, n)
if (lag < 0) {
xnew[1:(n-abs(lag))] <- x[(abs(lag)+1):n]
} else if (lag > 0) {
xnew[(lag+1):n] <- x[1:(n-lag)]
} else {
xnew <- x
}
return(xnew)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment