16

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.

4

2 回答 2

22

您可以使用 grepl 和 ifelse 语句:

> color = c("AliceBlue", "BlueViolet", "DarkRed", "MediumVioletRed")
> ifelse(grepl("Red",color),"red","other")
[1] "other" "other" "red"  "red" 
于 2015-02-07T17:12:32.090 回答
5

您不需要if或不需要ifelse此任务。您可以使用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" 

sub命令将包括子字符串在内的所有字符串替换"red""red". 此外,我指定ignore.case = TRUE了大写和小写匹配。

于 2015-02-07T17:31:48.740 回答