如何在if语句中使用grep

时间:2021-09-19 17:02:40

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.

在R中,我想在if语句中进行类似的操作,比如下面的示例,在mix$color列中搜索包含单词red的任何颜色,并在mix dataframe中设置一个新变量,将其设置为红色。

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

混合newcolor <——如果美元(grep(“红”,混合颜色)“红色”

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

这里有一些dataframe混合的样本数据:

AliceBlue BlueViolet DarkRed MediumVioletRed

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

警告信息:在if (grepl(“深红色”,混合$color) = TRUE)“red”:条件的长度为>1,只使用第一个元素

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).

我认为grepl应该返回一个真或假的布尔值,这样应该可以接受,但是我遗漏了一些东西(或很多)。

Thanks for your help.

谢谢你的帮助。

2 个解决方案

#1


15  

you can use grepl and an ifelse statement:

您可以使用grepl和ifelse语句:

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

#2


3  

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

对于这个任务,您不需要if或ifelse。您可以使用下标:

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.

子命令将包括子字符串“red”在内的所有字符串替换为“red”。此外,我指定的忽视。大小写=大小写匹配为真。

#1


15  

you can use grepl and an ifelse statement:

您可以使用grepl和ifelse语句:

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

#2


3  

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

对于这个任务,您不需要if或ifelse。您可以使用下标:

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.

子命令将包括子字符串“red”在内的所有字符串替换为“red”。此外,我指定的忽视。大小写=大小写匹配为真。