繁体   English   中英

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

[英]Delete rows containing specific strings in R

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

我的输入数据框:

   Value   Name 
    55     REVERSE223   
    22     GENJJS
    33     REVERSE456
    44     GENJKI

我的预期输出:

   Value   Name 
    22     GENJJS
    44     GENJKI

这应该可以解决问题:

df[- grep("REVERSE", df$Name),]

或者更安全的版本是:

df[!grepl("REVERSE", df$Name),]

您可以使用dplyr::filter()并否定grepl()匹配:

library(dplyr)

df %>% 
  filter(!grepl('REVERSE', Name))

或使用dplyr::filter()并否定stringr::str_detect()匹配:

library(stringr)

df %>% 
  filter(!str_detect(Name, 'REVERSE'))

实际上我会使用:

df[ grep("REVERSE", df$Name, invert = TRUE) , ]

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

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

stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
[1]  TRUE FALSE

如果它是多个字符串,则可以使用此函数df[!grepl("REVERSE|GENJJS", df$Name),]

您可以使用之前提供的代码在同一个数据帧 (df) 中使用它

df[!grepl("REVERSE", df$Name),]

或者您可以使用此代码为数据帧分配不同的名称

df1<-df[!grepl("REVERSE", df$Name),]

基于 BobD59 和隐藏层响应的迟到答案。

这将删除多个特定字符串,同时避免在任何行中不包含所需搜索词时删除所有记录。

df1 <-
   df[!grepl("REVERSE|GENJJS", df$Name), (invert = TRUE), ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM