【问题标题】:match products in a list in R匹配 R 列表中的产品
【发布时间】:2021-04-18 21:28:08
【问题描述】:

我必须对这些产品列表进行分类:

product_list<-data.frame(product=c('banana from ecuador 1 unit', 'argentinian meat (1 kg) cow','chicken breast','noodles','salad','chicken salad with egg'))

基于此向量的每个元素中包含的单词:

product_to_match<-c('cow meat','deer meat','cow milk','chicken breast','chicken egg salad','anana')

我必须将每个产品 product_to_match 的所有单词匹配到数据框的每个元素中。

我不确定最好的方法是什么,以便将每个产品分类到一个新列中,以便有这样的东西:

product_list<-data.frame(product=c('banana from ecuador 1 unit', 'argentinian meat (1 kg) 
cow','chicken breast','noodles','salad','chicken salad with egg'),class=c(NA,'cow meat','chicken 
breast',NA,NA,'chicken egg salad'))

请注意,'anana' 与 'banana' 不匹配,即使字符包含在字符串中但不包含单词。我不知道该怎么做。

谢谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    也许这会有所帮助

    q <- outer(
      strsplit(product_to_match, "\\s+"),
      strsplit(product_list$product, "\\s+"),
      FUN = Vectorize(function(x, y) all(x %in% y))
    )
    product_list$class <- product_to_match[replace(colSums(q * row(q)), colSums(q) == 0, NA)]
    

    这样

    > product_list
                          product             class
    1  banana from ecuador 1 unit              <NA>
    2 argentinian meat (1 kg) cow          cow meat
    3              chicken breast    chicken breast
    4                     noodles              <NA>
    5                       salad              <NA>
    6      chicken salad with egg chicken egg salad
    

    【讨论】:

    • outer 是一个不错的选择,因为它允许检查您是否也获得了多个匹配项。
    • 另外,主题变体 - product_to_match[max.col(cbind(outer( strsplit(product_list$product, "\\s+"), strsplit(product_to_match, "\\s+"), FUN = Vectorize(function(x, y) all(y %in% x)) ), TRUE), "first")]
    • @thelatemail 谢谢,这么紧凑的变体很酷。
    【解决方案2】:

    使用stringdist 可以获得一些匹配项

    library(fuzzyjoin)
    stringdist_left_join(product_list, tibble(product = product_to_match), 
            method = 'soundex')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多