Home > Mobile >  Replacing the contents of a vector with another R
Replacing the contents of a vector with another R

Time:10-31

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') 

CodePudding user response:

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.

  • Related