我有一个关于计算字符串中有多少个匹配模式的问题
例如, 我有一个数据框's'
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')
我想要的最终结果是这样的:
string count
'I have first and second' 2
'I have first' 1
'I have second and first and third' 3
现在我只能使用
grepl(paste(toMatch, collapse = "|"), s$string)
它将返回哪个字符串与 toMatch 中的任何元素匹配,但我如何知道匹配了多少个元素?
任何帮助将不胜感激!提前致谢!
最佳答案
data.frame(string=s$string, count=rowSums(sapply(toMatch, function(x) grepl(x, s$string))))
关于r - grep 多个模式并计算字符串 r 中有多少个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36187103/