删除R中包含特定字符串的行

use*_*668 46 string r rows match

我想排除包含字符串"REVERSE"的行,但我的行与单词完全不匹配,只包含它.

我的输入数据框:

   Value   Name 
    55     REVERSE223   
    22     GENJJS
    33     REVERSE456
    44     GENJKI
Run Code Online (Sandbox Code Playgroud)

我的预期产量:

   Value   Name 
    22     GENJJS
    44     GENJKI
Run Code Online (Sandbox Code Playgroud)

Pop*_*Pop 73

这应该做的伎俩:

df[- grep("REVERSE", df$Name),]
Run Code Online (Sandbox Code Playgroud)

或者更安全的版本是:

df[!grepl("REVERSE", df$Name),]
Run Code Online (Sandbox Code Playgroud)

  • 你说"更安全"是什么意思? (4认同)
  • @JasonMeloHall减号( - )运算符确实使用负索引和否定(!)运算符使用逻辑索引,因此否定运算符比减号( - )更安全 (3认同)
  • @nemja `grepl` 函数使用正则表达式进行匹配,其语法中 `(` 有意义。如果您设置命名参数 `fixed = TRUE` 那么 `grepl` 将执行文字匹配而不使用正则表达式,这应该适合您的用例。 (2认同)

小智 17

其实我会用:

df[ grep("REVERSE", df$Name, invert = TRUE) , ]
Run Code Online (Sandbox Code Playgroud)

如果所需的搜索词未包含在任何行中,这将避免删除所有记录.


bar*_*nus 6

您可以使用stringi包中的stri_detect_fixed 函数

stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
[1]  TRUE FALSE
Run Code Online (Sandbox Code Playgroud)


sbh*_*bha 6

您可以使用dplyr::filter()和取消grepl()匹配:

library(dplyr)

df %>% 
  filter(!grepl('REVERSE', Name))
Run Code Online (Sandbox Code Playgroud)

或与dplyr::filter()否定stringr::str_detect()匹配项:

library(stringr)

df %>% 
  filter(!str_detect(Name, 'REVERSE'))
Run Code Online (Sandbox Code Playgroud)

  • 这个问题要求很多字符串。那么如果你想删除多个字符串会发生什么,即`remove.list <- c("REVERSE", "FOO", "BAR, "JJ")` (2认同)