Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R how to use grep in if statement

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.

like image 755
Jazzmine Avatar asked Feb 07 '15 17:02

Jazzmine


2 Answers

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" 
like image 167
xraynaud Avatar answered Oct 22 '22 16:10

xraynaud


You don't need if or ifelse for this task. You can use sub:

color <- c("darkred", "indianred", "violetred", "deep red", 
           "Orange Red", "blue", "yellow")

sub(".*red.*", "red", color, ignore.case = TRUE)
# [1] "red"    "red"    "red"    "red"    "red"    "blue"   "yellow" 

The sub command replaces all strings including the substring "red" with "red". Furthermore, I specified ignore.case = TRUE for upper- and lowercase matches.

like image 5
Sven Hohenstein Avatar answered Oct 22 '22 15:10

Sven Hohenstein