Delete rows containing specific strings in R

北慕城南 提交于 2019-12-12 05:12:04

问题


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:

   Value   Name 
    55     REVERSE223   
    22     GENJJS
    33     REVERSE456
    44     GENJKI

My expected output:

   Value   Name 
    22     GENJJS
    44     GENJKI

回答1:


This should do the trick:

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

Or a safer version would be:

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



回答2:


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.




回答3:


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



回答4:


You can use stri_detect_fixed function from stringi package

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



回答5:


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),]


来源:https://stackoverflow.com/questions/34007025/r-remove-row-if-there-is-a-certain-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!