【问题标题】:What is wrong with my function and for-loop?我的函数和 for 循环有什么问题?
【发布时间】: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


【解决方案1】:

您可以向量化您的答案,以缩短您的代码并加快您的功能。一个例子是:

library(stringr)
number.countries <- function(str,dictionary){
  return(sum(str_count(str,dictionary)))
}
number.countries("England and Ireland, oh and also Wales", c("Wales","Ireland","England"))
[1] 3

可以传递自定义字典(在您的情况下为countries$Countries

【讨论】:

    【解决方案2】:

    我猜你有多个字符串要检查国家/地区,那么你可以这样做:

    # example data
    longstring <- c("The countries austria and Albania are in Europe, while Australia is not. Austria is the richest of the two European countries.",
                    "In this second sentence we stress the fact that Australia is part of Australia.")
    countries <- c("Austria","Albania","Australia","Azerbeyan")
    

    使用stringi-package 中的lapplystri_count_fixed(您可以在其中指定区分大小写的操作),您可以获得每个国家/地区的计数:

    library(stringi)
    l <- lapply(longstring, stri_count_fixed, pattern = countries, case_insensitive = TRUE)
    

    结果:

    [[1]]
    [1] 2 1 1 0
    
    [[2]]
    [1] 0 0 2 0
    

    现在您可以在数据框中转换它:

    countdf <- setNames(do.call(rbind.data.frame, l), countries)
    countdf$total <- rowSums(countdf)
    

    最终结果:

    > countdf
      Austria Albania Australia Azerbeyan total
    1       2       1         1         0     4
    2       0       0         2         0     2
    

    注意:

    为了演示case_insensitive = TRUE 的工作原理,我在longstring 中以较低的a 开头“Austria”

    【讨论】:

    • 很棒的代码。有什么办法可以合并 ignore.case = TRUE ?
    • @Lars 我用stri_count_fixed 的实现来更新我的答案,来自stringi-package 允许这样做。这能回答你的问题吗?
    猜你喜欢
    • 2011-04-23
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多