Home > Blockchain >  Removing rows that have slashes in a specific column
Removing rows that have slashes in a specific column

Time:01-18

In a data frame, I have some strings in a column that have /// in it. Is there a way for me to search for strings that have that /// pattern and remove that row completely?

I have this DF1:

Name Key group1 group2 group3
XAS /// HUA test1234 10 10 8
MPA1 /// AAS2 test4553 8 7 4
MPAS test3341 5 5 5
SSPA1 test2142 5 6 8
MAS61A test4722 6 7 4

Essentially, this dataframe is very large, and so I want to keyword search in the first column for that pattern, and if it is present, to drop that row. To get this as the result below. Whats the best way to do so? Thanks!

Name Key group1 group2 group3
MPAS test3341 5 5 5
SSPA1 test2142 5 6 8
MAS61A test4722 6 7 4
# DF1
Name <- c("XAS /// HUA", "MPA1 /// AAS2", "MPAS", "SSPA1", "MAS61A")
Key <- c("test1234", "test4553", "test3341", "test2142", "test4722")
group1 <- c(10, 8, 5, 5, 6)
group2 <- c(10, 7, 5, 6, 7)
group3 <- c(8, 4, 5, 8, 4)
DF1 <- data.frame(Name, Key, group1, group2, group3)

CodePudding user response:

Using negated grepl.

DF1[!grepl('/', DF1$Name), ]
#     Name      Key group1 group2 group3
# 3   MPAS test3341      5      5      5
# 4  SSPA1 test2142      5      6      8
# 5 MAS61A test4722      6      7      4

CodePudding user response:

You can combine str_detect with the operator !.

Code

library(dplyr)
library(stringr)

DF1 %>% 
  filter(!str_detect(Name,"//"))

Output

    Name      Key group1 group2 group3
1   MPAS test3341      5      5      5
2  SSPA1 test2142      5      6      8
3 MAS61A test4722      6      7      4
  • Related