Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple strings with the same in R

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'

like image 391
shecode Avatar asked Feb 02 '15 19:02

shecode


People also ask

How do you replace the same word in R?

You can replace the string or the characters in a vector or a data frame using the sub() and gsub() function in R.

How do I replace multiple characters in a string?

To replace multiple characters in a string:Store the characters to be replaced and the replacements in a list. Use a for loop to iterate over the list. Use the str. replace() method to replace each character in the string.

How do I replace one character with another in R?

To replace a first or all occurrences of a single character in a string use gsub(), sub(), str_replace(), str_replace_all() and functions from dplyr package of R. gsub() and sub() are R base functions and str_replace() and str_replace_all() are from the stringr package.

How do I replace NAS with 0 in R?

You can replace NA values with zero(0) on numeric columns of R data frame by using is.na() , replace() , imputeTS::replace() , dplyr::coalesce() , dplyr::mutate_at() , dplyr::mutate_if() , and tidyr::replace_na() functions.


2 Answers

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.

like image 192
Rentrop Avatar answered Sep 17 '22 15:09

Rentrop


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" 
like image 42
mlegge Avatar answered Sep 16 '22 15:09

mlegge