【问题标题】:R how to use grep in if statementR如何在if语句中使用grep
【发布时间】:2015-04-07 17:19:33
【问题描述】:

在 RI 中,想要在 if 语句中执行类似下面的示例,我在 mix$color 列中搜索包含单词 red 的任何颜色,并将 mix 数据框中的新变量设置为红色.

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

以下是数据框组合的一些示例数据:

爱丽丝蓝 紫罗兰色 深红 中紫红

我收到此错误消息:

警告信息: 在 if (grepl("deep red", mix$color) == TRUE) "red" : 条件长度 > 1 并且只使用第一个元素

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

感谢您的帮助。

【问题讨论】:

  • 这里需要矢量化的ifelse,而不是普通的 if 和 else。使用 grepl 时也不需要 == true。
  • 是的,这就像一个冠军。我之前曾考虑过使用 ifelse,但在 else 部分被难住了,但我只会为 else 引用 mix$newcolor。它将为空或具有转换后的值。谢谢。
  • ifelse 的一个优点是您可以轻松嵌套它们。假设您要将颜色矢量转换为“纯”颜色:color = c("AliceBlue", "BlueViolet", "DarkRed", "MediumVioletRed", "DarkGreen"); ifelse(grepl("Red",color),"red",ifelse(grepl("Green",color),"green",ifelse(grepl("Blue",color),"blue","other")))

标签: r if-statement grepl


【解决方案1】:

你可以使用 grepl 和 ifelse 语句:

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

【讨论】:

  • 谢谢,基本上是 docent discimus 提供的,但带有示例代码。
【解决方案2】:

此任务不需要 ififelse。你可以使用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-09-28
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2016-11-13
    相关资源
    最近更新 更多