通过 R 中的现有 stringdist 函数并行处理子集数据帧和批处理

问题描述

我继承了一个函数,使用 stringdist 包在两组名称之间运行模糊匹配,以计算两个字符串变量之间的距离并选择距离最小的匹配。

这很好,很好,非常适合我的需求除了我有一个包含 200,000 个候选名称的数据框,可以针对 135 万个名称的参考集运行。每个名称约 6 秒,这将失控。

我可以访问一个集群,所以我认为破解坚果的最快方法是批量处理它:将候选名称分成 4000 个名称的 50 个子集并并行运行它们。理想情况下,我会从头开始编写并行批处理脚本,但我没有经验且时间有限。

有没有办法获取现有脚本,在它周围放置一个包装器,将输入子集化,将其提供给脚本,然后并行运行它们?即使它返回 50 个单独的文件,我也很乐意自己将它们拼接在一起。

现有代码为:

    library(stringdist)
    # set up function
    fuzzymatch<-function(dat1,dat2,string1,string2,meth,id1,id2){
  #initialize Variables:
  matchfile <-NULL #iterate appends
  x<-nrow(dat1) #count number of rows in input,for max number of runs
  
  #Check to see if function has ID values. Allows for empty values for ID variables,simple list match
  if(missing(id1)){id1=NULL}
  if(missing(id2)){id2=NULL}
  
#Loop through dat1 dataset iteratively. This is a work around to allow for large datasets to be matched
  #Can run as long as dat2 dataset fits in memory. Avoids full Cartesian join.
  for(i in 1:x) {
    d<-merge(dat1[i,c(string1,id1),drop=FALSE],dat2[,c(string2,id2),drop=FALSE])#drop=FALSE to preserve 1var dataframe
    
    #Calculate String distatnce based method specified "meth"
    d$dist <- stringdist(d[,string1],d[,string2],method=meth,nthread=4)
    
    #dedupes A_names selects on the smallest distatnce.
    d<- d[order(d[,d$dist,decreasing = FALSE),]
    d<- d[!duplicated(d[,string1]),]
    
    #append demos on matched file
    matchfile <- rbind(matchfile,d)
    #print(paste(round(i/x*100,2),"% complete",sep=''))
  }
  return(matchfile)
}

Matched <- fuzzymatch(unmatched.names,Master.Taxonomy,"Submitted_Name","scientificName",meth="jw")
head(example)

玩具数据:

    unmatched.names <- data.frame(
'Submitted_Name' = c(
  'Phragmites australis (Cav.) Steud.','Molinia caerulea Moench','Potentilla erecta (L.) Räuschel','Cistus ladanifer subsp. ladanifer','Cirsium palustre Scop.','Dryopteris filix-mas (L.) Schott.','Glyceria fluitans R.Br.','Luzula campestris DC.','Rosmarinus officinalis de Noë ex Lange','Cerastium fontanum subsp. vulgare (Hartm.) Greuter & Burdet'))
   Master.Taxonomy <- data.frame(
  'scientificName' = c(
    'Phragmites australis (Cav.) Trin. ex Steud.','Molinia caerulea (L.) Moench','Potentilla erecta (L.) Raeusch.','Cistus ladanifer subsp. africanus Dans.','Cirsium pygmaeum Scop.','Dryopteris filix-mas (L.) Schott','Glyceria fluitans (L.) R.Br.','Luzula campestris (L.) DC.','Rosmarinus officinalis L.','Cerastium fontanum subsp. vulgare (Hartman) Greuter & Burdet'))
    
    ```

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)