How to replace multiple strings with the same in R

shecode picture shecode · Feb 2, 2015 · Viewed 10.3k times · Source

I have a string

vec = c('blue','red','flower','bee')

I want to convert different strings into the same in one line instead of seperately i.e. i could gsub blue and gsub red to make them both spell 'colour'. How can I do this in one line?

output should be: 'colour','colour','flower','bee'

Answer

Rentrop picture Rentrop · Feb 2, 2015
sub("blue|red", "colour", vec)

use "|" (meening or) between the words you want to sub. use sub to change only the first occurence and gsub to change multiple occurences within the same string. See ?gsub