R 计算包含定义的较短字符串的字符串数的有效方法

R 计算包含定义的较短字符串的字符串数的有效方法,r,R,我有一个包含短字符串的字符向量: short <- c("aaa", "bah", "dju", "kjs") short我们循环通过“short”向量,得到stru计数,并将其减少为单个逻辑向量,得到总和 library(stringr) sum(Reduce(`|`, lapply(short, str_count, string = long))) #[1] 4 stru count使用stringi函数,这不取决于向量的长度,使用上述数据只需0.09s system.time(

我有一个包含短字符串的字符向量:

short <- c("aaa", "bah", "dju", "kjs")

short我们循环通过“short”向量,得到
stru计数
,并
将其减少为单个逻辑向量,得到
总和

library(stringr)
sum(Reduce(`|`, lapply(short, str_count, string = long)))
#[1] 4

stru count
使用
stringi
函数,这不取决于
向量的
长度

,使用上述数据只需0.09s

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
数据:

库(gsubfn)

u这在我的笔记本电脑上大约需要0.12秒,
long
short
来自结尾的注释,长度分别为10000和1000。没有使用包——只用于生成示例数据

system.time(num <- length(grep(paste(short, collapse = "|"), long, perl = TRUE)))
   user  system elapsed 
   0.08    0.00    0.12 

system.time(num我知道我在问题中没有问这个问题,但是我如何分别计算每个
short
字符串的频率?@JackArnestad它应该是
sapply(short,function(x)sum(stru count(long,x)))
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)
system.time(num <- length(grep(paste(short, collapse = "|"), long, perl = TRUE)))
   user  system elapsed 
   0.08    0.00    0.12 
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)