TheRimalaya TheRimalaya - 3 months ago 5
R Question

replace a vector of patter with another vector in R

I have a situation like this,

a <- c("abc", "bcd", "def")
b <- c("pqr", "rat", "xyz")
c <- c("abc", "def", "abc", "bcd", "bcd", "abc", "def", "abc", "bcd")


I want a vector
d
(say) with each
c
replaced by values in
b
that matches
a
.

I can do
gsub
by searching each individual string, but how can I do with all of them together.

Answer

Is this what you want?

d <- b[match(c,a)]

# [1] "pqr" "xyz" "pqr" "rat" "rat" "pqr" "xyz" "pqr" "rat"