Skip to content

Instantly share code, notes, and snippets.

@vankesteren
Created November 28, 2022 19:27
Show Gist options
  • Save vankesteren/be6d9b951bf9868a458f8a463cdad221 to your computer and use it in GitHub Desktop.
Save vankesteren/be6d9b951bf9868a458f8a463cdad221 to your computer and use it in GitHub Desktop.
Ring shift right function in R
#' Function to shift the elements of a vector
#'
#' Shifting elements to the right by `shift`. Use
#' negative integers to shift to the left.
#' Elements on the right of the vector will enter
#' on the left of the vector (ring).
#'
#' @param x vector to shift
#' @param shift how many elements to shift by
#'
#' @return the vector `x`, elements shifted by `shift`
ring_shift_right <- function(x, shift = 1) {
P <- length(x)
x[(1:P + P - 1 - shift) %% P + 1]
}
@thomvolker
Copy link

Functionality to return a matrix with indicators

ring_shift_right <- function(x, shift = 1, perm.mat = F) {
  P <- length(x)
  if (perm.mat) {
    X <- matrix(0, P, P)
    X[(1:P - 1) * P + (1:P + P - 1 - shift) %% P + 1] <- 1
    t(X)
  }
  else {
    x[(1:P + P - 1 - shift) %% P + 1]
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment