# [R] replace values in vector from a replacement table

Liviu Andronic landronimirc at gmail.com
Mon Jul 30 17:53:08 CEST 2012

```Dear all
I've got stuck when trying to replace values in a vector by selecting
replacements from a replacement table. I'm trying to use only base
functions. Here's a dummy example:
> (x <- rep(letters,2))
 "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p"
"q" "r" "s" "t" "u" "v"
 "w" "x" "y" "z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l"
"m" "n" "o" "p" "q" "r"
 "s" "t" "u" "v" "w" "x" "y" "z"
> values <- c("aa", "a", "b", NA, "d", "zz")
> repl <- c("aa", "A", "B", NA, "D", "zz")
> (repl.tab <- cbind(values, repl))
values repl
[1,] "aa"   "aa"
[2,] "a"    "A"
[3,] "b"    "B"
[4,] NA     NA
[5,] "d"    "D"
[6,] "zz"   "zz"

Now I can easily compute all four combinations of 'match' and '%in%':
> (ind <- match(x, repl.tab[ ,1]))
  2  3 NA  5 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
NA NA NA NA  2  3 NA
  5 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> (ind <- match(repl.tab[ ,1], x))
 NA  1  2 NA  4 NA
> (ind <- x %in% repl.tab[ ,1])
  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE  TRUE  TRUE
 FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> (ind <- repl.tab[ ,1] %in% x)
 FALSE  TRUE  TRUE FALSE  TRUE FALSE

But how do I actually proceed to obtain the following vector?  Can it
be done without an explicit apply() or loop?
> res
 "A" "B" "c" "D" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p"
"q" "r" "s" "t" "u" "v"
 "w" "x" "y" "z" "A" "B" "c" "D" "e" "f" "g" "h" "i" "j" "k" "l"
"m" "n" "o" "p" "q" "r"
 "s" "t" "u" "v" "w" "x" "y" "z"

Regards
Liviu

--
Do you know how to read?
http://www.alienetworks.com/srtest.cfm