R how to use grep in if statement

Jazzmine picture Jazzmine · Feb 7, 2015 · Viewed 23.9k times · Source

In R I want to do a like in an if statement like the example below where I'm searching for any colors in the mix$color column that contain the word red and setting a new variable in the mix dataframe to the color red.

mix$newcolor <- if(grep("Red",mix$color) "red"

And here's some sample data for the dataframe mix:

AliceBlue BlueViolet DarkRed MediumVioletRed

I'm getting this error message:

Warning message: In if (grepl("deep red", mix$color) == TRUE) "red" : the condition has length > 1 and only the first element will be used

I think that grepl should be returning a TRUE or FALSE boolean value so that should be acceptable but I'm missing something (or a lot).

Thanks for your help.

Answer

xraynaud picture xraynaud · Feb 7, 2015

you can use grepl and an ifelse statement:

> color = c("AliceBlue", "BlueViolet", "DarkRed", "MediumVioletRed")
> ifelse(grepl("Red",color),"red","other")
[1] "other" "other" "red"  "red"