Home > database >  How remove all rows with a specific string?
How remove all rows with a specific string?

Time:12-26

# A tibble: 4 x 1
   `134518d.g6`
      <chr>       
    1 134519dg6   
    2 134520d.g6  
    3 134521d.g6 
    4 134522dg6

This is part of my code. I want to remove all rows that contain .g and keep the rest rows (the first and fourth row in this code).

Tried to use this

df<-df1[! grepl(".g",df1$`134518d.g6`),]

but it didn't remove the unwanted rows.

CodePudding user response:

You can try this. The . has to be escaped, otherwise it stands for any character.

!grepl("\\.g",df1$'134518d.g6')
[1]  TRUE FALSE FALSE  TRUE

# and then use it on the data
df1[!grepl("\\.g",df1$'134518d.g6'),]
# A tibble: 2 x 1
  `134518d.g6`
  <chr>       
1 134519dg6   
2 134522dg6

CodePudding user response:

We could use str_detect from stringr package and negate (!) filter for pattern with escaping . with \\:

library(dplyr)
library(stringr)

df %>% 
  filter(!str_detect(`134518d.g6`, '\\.g6'))
 `134518d.g6`
  <chr>       
1 134519dg6   
2 134522dg6  
  •  Tags:  
  • r
  • Related