2016-03-23 12 views
2

dize r aldığım bir dataframe 's'grep birden desen ve saymak kaç ben bir dize örneğin</p> <p>, içinde eşleştirildiyse kaç sayımı ile ilgili bir soru var

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

ve

: toMatch

adlı bir eşleşme düzeni vektör
toMatch <- c('first', 'second', 'third') 

istediğim nihai sonuç gibidir

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

şimdi sadece

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

o toMatch içinde elemanın herhangi maçları hangi dize beni dönecektir kullanabilirsiniz, ancak nasıl eşleştirildiği kaç eleman bilebilirim?

Herhangi bir yardım için teşekkür ederiz! Şimdiden teşekkürler! Daha hızlı olabilir

cevap

2
data.frame(string=s$string, count=rowSums(sapply(toMatch, function(x) grepl(x, s$string)))) 
+0

teşekkürler! İşe yarıyor! ^^ –

1

başka olasılık:

Kişisel Veri:

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') 

Yaklaşım:

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 
İlgili konular