Delete rows containing specific strings in R

前端 未结 6 1587
暖寄归人
暖寄归人 2020-11-27 11:34

I would like to exclude lines containing a string \"REVERSE\", but my lines do not match exactly with the word, just contain it.

My input data frame:



        
相关标签:
6条回答
  • 2020-11-27 11:56

    You can use this function if it's multiple string df[!grepl("REVERSE|GENJJS", df$Name),]

    0 讨论(0)
  • 2020-11-27 12:01

    This should do the trick:

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

    Or a safer version would be:

    df[!grepl("REVERSE", df$Name),]
    
    0 讨论(0)
  • 2020-11-27 12:02

    You can use stri_detect_fixed function from stringi package

    stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
    [1]  TRUE FALSE
    
    0 讨论(0)
  • 2020-11-27 12:05

    Actually I would use:

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

    This will avoid deleting all of the records if the desired search word is not contained in any of the rows.

    0 讨论(0)
  • 2020-11-27 12:13

    You could use dplyr::filter() and negate a grepl() match:

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

    Or with dplyr::filter() and negating a stringr::str_detect() match:

    library(stringr)
    
    df %>% 
      filter(!str_detect(Name, 'REVERSE'))
    
    0 讨论(0)
  • 2020-11-27 12:23

    You can use it in the same datafram (df) using the previously provided code

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

    or you might assign a different name to the datafram using this code

    df1<-df[!grepl("REVERSE", df$Name),]
    
    0 讨论(0)
提交回复
热议问题