R/utils.R

Defines functions shift

Documented in shift

#' Function that shifts vector values to right or left
#'
#' Taken from https://stackoverflow.com/questions/26997586/shifting-a-vector by
#'   user petermeissner.
#' @param x Vector for which to shift values
#' @param n Number of places to be shifted.
#'    Positive numbers will shift to the right by default.
#'    Negative numbers will shift to the left by default.
#'    The direction can be inverted by the invert parameter.
#' @param invert Whether or not the default shift directions
#'    should be inverted.
#' @param default The value that should be inserted by default.
#' @export

shift <- function(x, n, invert=FALSE, default=NA){
  stopifnot(length(x)>=n)
  if(n==0){
    return(x)
  }
  n <- ifelse(invert, n*(-1), n)
  if(n<0){
    n <- abs(n)
    forward=FALSE
  }else{
    forward=TRUE
  }
  if(forward){
    return(c(rep(default, n), x[seq_len(length(x)-n)]))
  }
  if(!forward){
    return(c(x[seq_len(length(x)-n)+n], rep(default, n)))
  }
}
andrew-edwards/EDMsimulate documentation built on Oct. 25, 2023, 2:43 p.m.