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

Keep only rows containing certain string from a list of strings provided

How do I keep only rows that contain a certain string given a list of strings. What I’m trying to say is I don’t want to use grepl() and hardcode the values I would like to exclude. Let’s assume that I want to only keep records that contain abc or bbc or bcc or 20 more options in one of the columns, and I have x <- c("abc", "bbc", ....).

What can I do to only keep records containing values of x in the dataframe?

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

>Solution :

You can use %in%:

df_out <- df[df$v1 %in% x, ]

Or, you could form a regex alternation with the values in x and then use grepl:

regex <- paste0("^(?:", paste(x, collapse="|"), ")$")
df_out <- df[grepl(regex, df$v1), ]
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