R更快的替代str_contains

问题描述

我有一张桌子和一个字符向量:

ACT_Suburbs_Names <- data.table(DivisionNm = c('ACTON','AINSLIE','AMAROO','araNDA','BANKS'))

temp1 <- c('U1 336 DOORING ST ACTON','65/78 ACHELON DR MOORONG')

下面的脚本检查temp1中的地址是否在ACT_Suburbs_Names的地址列表中。

future_sapply(temp1,function(x) str_contains(ACT_Suburbs_Names,x,ignore.case = TRUE)) 

处理我得到的所有数据需要花费大量时间。 快一点吗?即使在python中也可以。

解决方法

创建模式并使用正则表达式:

> library(tidyverse)
> 
> ACT_Suburbs_Names <-  c('ACTON','AINSLIE','AMAROO','ARANDA','BANKS')
> 
> pat <- paste(ACT_Suburbs_Names,collapse = '|')
> 
> temp1 <- c('U1 336 DOORING ST ACTON',+  '65/78 ACHELON DR MOORONG',+  'asdf ARANDA asdfsadf',+           ' asdfasfd   BANK asdf',+           ' sdafasdf  BANKS  asdf',+           ' just junk') 
> 
> # find out which entries match - return the index of a match
> 
> grep(pat,temp1)
[1] 1 3 5
>