Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading