edge selcuk
edge selcuk

Reputation: 179

Replacing the contents of a vector with another R

How would I be able to make a new vector vectB where it replaces the contents of vectA ('ab','cd','bc') with 'aa','bb','cc'. So the output of vectB would be 'aa','bb','aa','cc'. The contents of vectA would be unchanged.

vectA <- c('ab','cd','ab','bc') 

Upvotes: 0

Views: 36

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145765

One common approach is to use a named vector, where the values are the desired values, and the names are the old values.

lookup = c("ab" = 'aa', 'cd' = 'bb', 'bc' = 'cc')

vectB = unname(lookup[match(vectA, names(lookup))])
vectB
[1] "aa" "bb" "aa" "cc"

Another common approach is to use factor labels. (You can of course use as.character after if you don't want a factor class result.)

B = factor(vectA, levels = c("ab", "cd", "bc"), labels = c("aa", "bb", "cc"))
B
# [1] aa bb aa cc
# Levels: aa bb cc

These both assume that all values in A will be present in the recoding lookup.

Upvotes: 1

Related Questions