How to replace multiple strings with the same in R

∥☆過路亽.° 提交于 2019-11-27 09:42:07
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" 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!