Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

grep for names with variable number of forward slashes

I have a column with two types of names (embedded within a longer string).

names are like A/HK/RATATA/Lol(2007) or A/chickapig/RATATA/Lol(2003).

I would like to filter using a regular expression based on the number of "/" within each name.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example: 
Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))
Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))
Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))
Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))

I would only like to filter the row containing Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))

I tried using \ to scape /, not even sure if it makes sense.

Thanks in advance for your help.

>Solution :

If it is based on the count of /, use str_count to filter the rows

library(dplyr)
n <- 3
df %>%
   filter(str_count(col1, fixed("/")) ==  n)

-output

                                           col1
1 Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))

data

df <- structure(list(col1 = c("Influenza A virus (A/chicken/Wenzhou/642/2013(H9N2))", 
"Influenza A virus (A/chicken/Wenzhou/643/2013(H9N2))", "Influenza A virus (A/chicken/Wenzhou/644/2013(H9N2))", 
"Influenza A virus (A/Wenzhou/mamamam/2013(H9N2))")),
 class = "data.frame", row.names = c(NA, 
-4L))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading