【问题标题】:Partial match for a dataset using vector in R使用 R 中的向量对数据集进行部分匹配
【发布时间】:2020-03-10 03:13:18
【问题描述】:

我有一个数据集,其中包含汽车品牌名称和其他数据 (test1),以及一个包含所有唯一缩短的汽车品牌名称的向量 (test)。

test<-c("Rolls Royce", "Toyota", "Tesla", "BMW","Ford", "Mercedes")
test1<- data.frame(Brand = c("Mercedes Benz", "Bayerische Motoren Werke (BMW)",
                 "Ford Motor Corp.", "Rolls Royce", 
                 "Tesla", "Mercedes Benz", "Ford Motor"),
      Ratings = c(6,6,4,9,8,8,6))

如何使用唯一汽车名称的字符串向量 (test) 对数据集 (test1) 进行部分字符串匹配并更改 的 Brand 值>test1 来搜索和匹配 test 的值?

我可以为每个条目都这样做,但我想看看是否有更快的方法来获得结果:

library(data.table)
test1[test1$Brand %like% "Rolls Royce", ]$Brand <-"Rolls Royce"
test1[test1$Brand %like% "Toyota", ]$Brand <-"Toyota"
test1[test1$Brand %like% "Tesla", ]$Brand <-"Tesla"
test1[test1$Brand %like% "BMW", ]$Brand <-"BMW"
test1[test1$Brand %like% "Ford", ]$Brand <-"Ford"
test1[test1$Brand %like% "Mercedes", ]$Brand <-"Mercedes"

这是我想为上述示例获得的结果:

data.frame(Brand = c("Mercedes", "BMW",
                 "Ford", "Rolls Royce", 
                 "Tesla", "Mercedes", "Ford"),
      Ratings = c(6,6,4,9,8,8,6))

【问题讨论】:

    标签: r nlp stringr


    【解决方案1】:

    我们可以将test中的字符串粘贴在一起,使用str_extract

    stringr::str_extract(test1$Brand, paste0('\\b', test, '\\b', collapse = "|")) 
    #[1] "Mercedes" "BMW"  "Ford"   "Rolls Royce" "Tesla"  "Mercedes"    "Ford"  
    

    在模式中添加了单词边界 (\\b) 以避免匹配不完整的单词,例如 "ford""afford" 匹配。

    【讨论】:

      【解决方案2】:

      使用agrep模糊匹配。

      test1 <- transform(test1, 
                         Brand.new=gsub("\\d+$", "", names(sort(unlist(sapply(test, function(x) 
                           agrep(x, Brand)))))))
      test1
      #                            Brand Ratings   Brand.new
      # 1                  Mercedes Benz       6    Mercedes
      # 2 Bayerische Motoren Werke (BMW)       6         BMW
      # 3               Ford Motor Corp.       4        Ford
      # 4                    Rolls Royce       9 Rolls Royce
      # 5                          Tesla       8       Tesla
      # 6                  Mercedes Benz       8    Mercedes
      # 7                     Ford Motor       6        Ford
      

      【讨论】:

        猜你喜欢
        • 2019-09-19
        • 1970-01-01
        • 2021-07-21
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 2021-02-20
        • 2015-05-18
        • 1970-01-01
        相关资源
        最近更新 更多