【问题标题】:make a fuzzyjoin and keep only exact match when there is one, keep all options otherwise进行模糊连接并仅在有一个时保留完全匹配,否则保留所有选项
【发布时间】:2020-11-26 14:34:52
【问题描述】:

我有两个数据框,我正在尝试根据国家/地区名称字段加入,我想要实现的是:当找到完美匹配时,我想只保留那一行,否则我想显示所有行/选项。

library(fuzzyjoin)

df1 <- data.frame(
  country = c('Germany','Germany and Spain','Italy','Norway and Sweden','Austria','Spain'),
  score = c(7,8,9,10,11,12)
)

df2 <- data.frame(
  country_name = c('Germany and Spain','Germany','Germany.','Germania','Deutschland','Germany - ','Spun','Spain and Portugal','Italy','Italia','Greece and Italy',
                   'Australia','Austria...','Norway (Scandinavia)','Norway','Sweden'),
  comments = c('xxx','rrr','ttt','hhhh','gggg','jjjj','uuuuu','ooooo','yyyyyyyyyy','bbbbb','llllll','wwwwwww','nnnnnnn','cc','mmmm','lllll')
)

j <- regex_left_join(df1,df2, by = c('country' = 'country_name'), ignore_case = T)

结果 (j) 显示 'Germany and Spain' 出现了 3 次,第 1 次出现是完美匹配,我想只保留这一个并摆脱其他两个。 “挪威和瑞典”没有完美的匹配,所以我想保留两个可能的选项/行(原样)。

我该怎么做?

【问题讨论】:

    标签: r join match fuzzyjoin


    【解决方案1】:

    您可以使用stringdist::stringdist 计算匹配项之间的距离,对于存在完全匹配项的条目,请仅保留:

    library(dplyr)
    j %>% 
      mutate(dist = stringdist::stringdist(country, country_name)) %>% # add distance
      group_by(country) %>%                                            # group entries
      mutate(exact = any(dist == 0)) %>%                               # check if exact match exists in group
      filter(!exact | dist == 0) %>%                                   # keep only entries where no exact match exists in the group OR where the entry is the exact match
      ungroup()
    #> # A tibble: 5 x 6
    #>   country           score country_name      comments    dist exact
    #>   <chr>             <dbl> <chr>             <chr>      <dbl> <lgl>
    #> 1 Germany               7 Germany           rrr            0 TRUE 
    #> 2 Germany and Spain     8 Germany and Spain xxx            0 TRUE 
    #> 3 Italy                 9 Italy             yyyyyyyyyy     0 TRUE 
    #> 4 Norway and Sweden    10 Norway            mmmm          11 FALSE
    #> 5 Norway and Sweden    10 Sweden            lllll         11 FALSE
    

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2021-11-25
      相关资源
      最近更新 更多