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

How to use multiple keywords in grepl

Here is a vector of type string:

a<-c("Recherche impliquant la personne humaine (RIPH) Médicaments 3",
 "Recherche impliquant la personne humaine (RIPH) Hors Produits de santé 3",
 "Recherche impliquant la personne humaine (RIPH) dispositif médical 1")

I want to identify all element containing some keywords:

I firstly identify all element containing the word "Recherche"

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

grepl("recherche",a,ignore.case = TRUE)

[1] TRUE TRUE TRUE

Now I want to identify only elements containing all these keywords at the same time:

c("recherche", "impliquant", "personne", "humaine", "3")

The result must be

[1] TRUE TRUE FALSE

I tried this:

grepl(c("Recherche,impliquant , personne, humaine, 3"),a)

but it didn’t work, cause the output is that:

FALSE FALSE FALSE

>Solution :

You can do it using multiple lookaheads (?=...), where each lookahead asserts the presence anywhere in the string of a keyword; (?i) is used to make the matching case-insensitive:

grep("(?i)(?=.*recherche.*)(?=.*impliquant.*)(?=.*personne.*)(?=.*humaine.*)(?=.*3.*).*", 
 a,
 value = TRUE,
 perl = TRUE) 
[1] "Recherche impliquant la personne humaine (RIPH) Médicaments 3"           
[2] "Recherche impliquant la personne humaine (RIPH) Hors Produits de santé 3"

This method obviously also works with grepl; just omit `value = TRUE:

grepl("(?i)(?=.*recherche.*)(?=.*impliquant.*)(?=.*personne.*)(?=.*humaine.*)(?=.*3.*).*", 
     a,
     perl = TRUE) 
[1]  TRUE  TRUE FALSE
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