How to replace multiple strings with the same in R
Asked Answered
A

3

10

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'

Aflcio answered 2/2, 2015 at 19:42 Comment(0)
L
17
sub("blue|red", "colour", vec)

use "|" (which means the logical OR operator) between the words you want to substitute.

Use sub to change only the first occurence and gsub to change multiple occurences within the same string.

Type ?gsub into R console for more information.

Looming answered 2/2, 2015 at 19:44 Comment(2)
will this work if my actual string consists of phrases?Aflcio
yes. Try it with sentence <- c("my favourite color is blue, red is what i dont like", "flowers are great") and see the difference between sub and gsubLooming
C
4

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" 
Conferva answered 2/2, 2015 at 19:47 Comment(0)
M
0
library(mgsub)

mgsub(vec, c('blue', 'red'), 'colour', recycle = TRUE)
# [1] "colour" "colour" "flower" "bee"   
Motheaten answered 3/4, 2024 at 17:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.