Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
grep多个模式并计算字符串r中有多少个模式_R_Design Patterns_Count_Match - Fatal编程技术网

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