Sylvain Mareschal, Ph.D.
Bioinformatics engineer
August 6, 2011 at 15:02
swap()
swap.R (click to download)

This function replaces various values by others in a character vector. It is particulary useful when replacing codes by descriptive strings, and when merging various codes into the same category.

Usage
source("http://bioinformatics.ovsa.fr/files/swap.R")
swap(x, swap=list(), empty.make=NULL, na.make=NULL, na.del=NULL)


Arguments
x : The vector to transform.
swap : A named list of vectors. For each element in the list, all values listed in the vector will be replaced by the name of the vector. See examples.
empty.make : A vector of values to replace by empty strings.
na.make : A vector of values to replace by NA.
na.del : A single value to replace NA with.

Value
Usually a character vector, as list names have to be of type character.
Can be x type if no replacement involving the swap argument is used.

Example : Replace all "A" with "D"
vec = c("A", "B", "A", "C")
print(vec)
vec = swap(vec, list("D"="A"))
print(vec)

Example : NA management
vec = c(NA, "B", NA, "C")
print(vec)
vec = swap(vec, na.make="B", na.del="a")
print(vec)

Example : Complex example
vec = c(-2:9, NA)
print(vec)
vec = swap(
  x = vec,
  swap = list(
    "null" = 0,
    "odd" = seq(from=1, to=max(vec, na.rm=TRUE), by=2),
    "even" = c(2, 4, 6, 8)
  ),
  na.make = c(-2, -1),
  na.del = "former NA value"
)
print(vec)