R/recode.R

Defines functions recode

Documented in recode

#' Recode a vector
#'
#' @param x     a vector
#' @param from  values to recode
#' @param to    target values
#' @param other the rest is recoded to those
#' 
#' @export

recode <- function(x, from, to, other) {
  stopifnot(length(from) == length(to))
  
  new_x <- x
  k <- length(from)
  for (i in 1:k) new_x[x == from[i]] <- to[i]
  
  if (!missing(other) && length(other) > 1) {
    new_x[!(x %in% from)] <- other[1]
    warning("'other' has length > 1 and only the first element will be used")
  }
  
  new_x
}
twolodzko/twextras documentation built on May 3, 2019, 1:52 p.m.