【问题标题】:agrep output approximate macthingagrep 输出近似运算
【发布时间】:2018-01-18 11:54:36
【问题描述】:

 agrep('timothy', c('timo','tim','timoth', 'timothys'), max.distance = 0.01, value=TRUE)

我想将原始字符串和所有可能的结果一起输出到一个数据框中,如下所示。

Original Replace1 Replace2
timothy  timoth   timothys

这是可能的还是有更好的功能可以使用?

【问题讨论】:

    标签: r fuzzy-comparison agrep


    【解决方案1】:

    我个人会将其保留为“长”格式而不是宽格式(您以后可以随时对其进行转换):

    data.frame(
      original = "timothy",
      replacement = agrep('timothy', c('timo','tim','timoth', 'timothys'), max.distance = 0.01, value=TRUE),
      stringsAsFactors=FALSE
    )
    ##   original replacement
    ## 1  timothy      timoth
    ## 2  timothy    timothys
    

    您可能希望多次执行此操作,因此我将其设为函数。而且,由于agrep() 的输出可以character(0),我们需要处理它,所以我们也将添加一个辅助函数:

    `%|l0%` <- function(x, y) if (length(x) == 0) y else x
    
    agrep_to_data_frame <- function(pattern, x, max.distance=0.01, costs=NULL) {
      data.frame(
        original = pattern,
        replacement = agrep(pattern, x, max.distance = max.distance, value=TRUE) %|l0% NA_character_,
        stringsAsFactors=FALSE
      )
    } 
    

    而且,现在它是一个调用,您可以在purrr::map2()mapply() 等中使用它。

    agrep_to_data_frame('timothy', c('timo','tim','timoth', 'timothys'))
    ##   original replacement
    ## 1  timothy      timoth
    ## 2  timothy    timothys
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多