R find two words into same string

Viewed 77

I want to create a single regex or str_detect (if possible) to search through text strings and determine if two words (countries) occur in the same string based on one country list, but testing without repetition. For example:

latam <- c("BRAZIL", "MEXICO", "CHILE", "ARGENTINA", "COLOMBIA", "CUBA", "VENEZUELA", "PERU", "COSTA RICA", "ECUADOR", "URUGUAY", "BOLIVIA", "PARAGUAY", "GUATEMALA", "EL SALVADOR", "PANAMA", "NICARAGUA", "DOMINICAN REPUBLIC", "HONDURAS", "HAITI")

example_string <- c("USA;BRAZIL", "USA;BRAZIL;ARGENTINA", "BRAZIL;BRAZIL;ARGENTINA", "BRAZIL;ARGENTINA", "BRAZIL;BRAZIL", "BRAZIL;BRAZIL;ARGENTINA;ARGENTINA")

Testing example_string, the desired output is: FALSE, TRUE, TRUE, TRUE, FALSE, TRUE.

1 Answers

a data.table solution (for sure there's a regex for this, but...)

library(data.table)
a <- data.table(example_string) 

create a data.table with the test string

 a[, countries := sapply(example_string, strsplit, ";")] 

split the countries, so each one can be tested individually

a[, sum(unique(countries[[1]]) %in% latam) >= 2, by = example_string] 

find how many UNIQUE countries of each row are in the latam list and check if the number is equal or greater than 2.

Related