grep多个模式并计算字符串r中有多少个模式
我有一个问题,关于计算一个字符串中有多少匹配的模式 比如说,, 我有一个数据帧'grep多个模式并计算字符串r中有多少个模式,r,design-patterns,count,match,R,Design Patterns,Count,Match,我有一个问题,关于计算一个字符串中有多少匹配的模式 比如说,, 我有一个数据帧' index string 1 'I have first and second' 2 'I have first' 3 'I have second and first and third' 和一个叫做toMatch的匹配模式向量 toMatch <- c('first', 'second', 'third') 现在我只能用 grepl(paste(toMatch, co
index string
1 'I have first and second'
2 'I have first'
3 'I have second and first and third'
和一个叫做toMatch的匹配模式向量
toMatch <- c('first', 'second', 'third')
现在我只能用
grepl(paste(toMatch, collapse = "|"), s$string)
它将返回哪个字符串匹配toMatch中的任何元素,但我如何知道匹配了多少元素
任何帮助都将不胜感激!提前谢谢 另一种可能更快:
data.frame(string=s$string, count=rowSums(sapply(toMatch, function(x) grepl(x, s$string))))
您的数据:
dat <- read.table(text="index string
1 'I have first and second'
2 'I have first'
3 'I have second and first and third'", header=TRUE)
toMatch <- c('first', 'second', 'third')
dat
dat <- read.table(text="index string
1 'I have first and second'
2 'I have first'
3 'I have second and first and third'", header=TRUE)
toMatch <- c('first', 'second', 'third')
library(stringi)
dat$count <- stri_count_regex(dat$string, paste(toMatch, collapse="|"))
dat
## index string count
## 1 1 I have first and second 2
## 2 2 I have first 1
## 3 3 I have second and first and third 3