【问题标题】:R: agrep with vector patternR:带有矢量模式的 agrep
【发布时间】:2015-10-04 18:48:24
【问题描述】:

我有一个模式向量,需要在它们上使用agrep。问题是agrep 似乎一次只采用一种模式。

patt <- c("test","10 Barrel")
lut  <- c("1 Barrel","10 Barrel Brewing","Harpoon 100 Barrel Series","resr","rest","tesr")

for (i in 1:length(patt)) {
  print(agrep(patt[i],lut,max=1,v=T))
}

结果:

[1] "rest" "tesr"
[1] "1 Barrel"                  "10 Barrel Brewing"         "Harpoon 100 Barrel Series"

for 在长模式上很慢,因此尝试以矢量化形式进行:

VecMatch1 = function(string, stringVector){
  stringVector[agrep(string, stringVector, max = 1)]
}
a = VecMatch1(patt,lut)

Warning message:
In agrep(string, stringVector, max = 1) :
  argument 'pattern' has length > 1 and only the first element will be used

lapply 等函数可能有帮助吗?谢谢!!

【问题讨论】:

    标签: r fuzzy-search agrep


    【解决方案1】:

    使用lapply

    lapply(patt, agrep, x=lut, max.distance=c(cost=1, all=1), value=TRUE)
    
    [[1]]
    [1] "rest" "tesr"
    
    [[2]]
    [1] "1 Barrel"                  "10 Barrel Brewing"         "Harpoon 100 Barrel Series"
    

    您可能可以使用 dplyr 或 data.table 获得更快的性能。

    【讨论】:

    • 好的,谢谢!我尝试了lapply,但使用了错误的语法 - 没有将函数放在正确的位置
    • 事实证明,这两种方法的速度相当。
    • 你会如何使用 dplyr 或 data.table 来处理它?
    猜你喜欢
    • 2022-11-24
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多