【发布时间】:2018-03-14 16:26:45
【问题描述】:
我目前正在尝试计算一长串国家的绝对数量。我已经加载了一个名为“国家”的数据框,其中包含“国家”列,由世界上所有国家组成。 我想创建一个搜索任何字符串的函数,遍历我的 df 中的所有国家/地区名称并返回任何国家/地区名称出现的总和。 (即提及的国家总数)
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
【问题讨论】:
-
看起来你的参数 str 没有初始化。因此不适用?
标签: r function for-loop if-statement grepl