I am currently trying to count the absolute number of countries in a long string. I have loaded a data frame named "countries" with column "Countries", consisting of all countries in the world. I want to make a function that searches any string, loop over all the country-names in my df and return the sum of occurrences of any country-name. (I.e. the total number of countries mentioned)
Code:
number.of.countries <- function(str){
# #Initialize
countcountry <- 0
# #loop over all countries:
for (i in countries$Countries){
# #Logical test:
countries_mentioned <- grepl(i, str, perl = T, ignore.case = T)
# #add to the count
if (isTRUE(countries_mentioned)){
countcountry <- countcountry + str_count(str, fixed(countries$Countries[i], ignore_case = TRUE))
}
}
#Output
return(countcountry)
}
###When running the function:
> number.of.countries(str)
[1] NA
Aucun commentaire:
Enregistrer un commentaire