mercredi 23 mars 2016

grep multiple patterns and count how many in the string r

I got a question about count how many matched pattern in a string

for example, I got a dataframe 's'

index  string
1      'I have first and second'
2      'I have first'
3      'I have second and first and third'

and a match pattern vector called toMatch

toMatch <-  c('first', 'second', 'third')

the final result I want is like:

string                              count
'I have first and second'           2
'I have first'                      1
'I have second and first and third' 3

now I can only use

grepl(paste(toMatch, collapse = "|"), s$string) 

it will return me which string matches any of element in toMatch, but how can I know how many element are matched?

Any help would be appreciate! Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire