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'
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
Here you do not need to specify the colors to be replaced, it will replace any color that R knows about (returned by colors()
)
> col <- paste0(colors(), collapse = "|")
> gsub(col, "colour", vec)
[1] "colour" "colour" "flower" "bee"
Also, as suggested in the comments (which will obviously only work if the element is the color only, so the gsub
method seems better suited to your purposes):
> vec[vec %in% colors()] <- "coulour"
> vec
[1] "coulour" "coulour" "flower" "bee"
来源:https://stackoverflow.com/questions/28285480/how-to-replace-multiple-strings-with-the-same-in-r