[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))
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p"
"q" "r" "s" "t" "u" "v"
[23] "w" "x" "y" "z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l"
"m" "n" "o" "p" "q" "r"
[45] "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]))
 [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
[30]  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))
[1] NA  1  2 NA  4 NA
> (ind <- x %in% repl.tab[ ,1])
 [1]  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
[15] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE  TRUE  TRUE
[29] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE
[43] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> (ind <- repl.tab[ ,1] %in% x)
[1] 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
 [1] "A" "B" "c" "D" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p"
"q" "r" "s" "t" "u" "v"
[23] "w" "x" "y" "z" "A" "B" "c" "D" "e" "f" "g" "h" "i" "j" "k" "l"
"m" "n" "o" "p" "q" "r"
[45] "s" "t" "u" "v" "w" "x" "y" "z"


Regards
Liviu


-- 
Do you know how to read?
http://www.alienetworks.com/srtest.cfm
http://goodies.xfce.org/projects/applications/xfce4-dict#speed-reader
Do you know how to write?
http://garbl.home.comcast.net/~garbl/stylemanual/e.htm#e-mail



More information about the R-help mailing list