[英]Efficient way to calculate number of strings which contain a defined shorter string
我有一個包含短字符串的字符向量:
short <- c("aaa", "bah", "dju", "kjs")
我想計算下面向量中的字符串數,其中至少有一個上面的短字符串存在。
long <- c("aaajhd", "slilduaaadifh", "sldifjsdbahsdofiusd", "sdflisjdjukjs", "sldifjbak", "sdfoiuwebss", "sdkfuhsd", "sdlfihwoio")
它應輸出的數字是4,因為long
向量中的4個字符串包含short
向量中定義的較短字符串。
我的實際短向量大約是10000個字符串,長大約是1000,所以我正在尋找一種有效的方法來計算它。
謝謝!
這發生在我的筆記本電腦約0.12 seconds其中long
和short
距離末的注意,並有長度10000個1000沒有軟件包使用-只生成樣本數據。
system.time(num <- length(grep(paste(short, collapse = "|"), long, perl = TRUE)))
user system elapsed
0.08 0.00 0.12
相比之下,Reduce / str_count解決方案需要6.5秒。
注意:我們將Ulysses一書中的前1000個和10000個單詞作為樣本數據。
library(gsubfn)
u <- "http://www.gutenberg.org/files/4300/4300-0.txt"
joyce <- readLines(u)
joycec <- paste(joyce, collapse = " ")
words <- strapplyc(joycec, "\\w+")[[1]]
short <- head(words, 1000)
long <- head(words, 10000)
我們遍歷'short'向量,獲取str_count
並將其Reduce
為單個邏輯向量以獲得sum
library(stringr)
sum(Reduce(`|`, lapply(short, str_count, string = long)))
#[1] 4
str_count
使用stringi
函數,這不依賴於vector
的length
使用上面提供的數據,這只需要0.09秒。
system.time(sum(sapply(regmatches(long, gregexpr(paste(short, collapse = "|"), long, ignore.case = F, perl = T)), length) >= 1))
User System verstrichen
0.09 0.00 0.09
數據:
library(gsubfn)
u <- "http://www.gutenberg.org/files/4300/4300-0.txt"
joyce <- readLines(u)
joycec <- paste(joyce, collapse = " ")
words <- strapplyc(joycec, "\\w+")[[1]]
short <- head(words, 1000)
long <- head(words, 10000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.