Edited df
and dict
I have a data frame containing sentences:
df <- data_frame(text = c(\"I love pandas
A bit of double looping via sapply
and gregexpr
:
res <- sapply(dict$word, function(x) {
sapply(gregexpr(x,df$text),function(y) length(y[y!=-1]) )
})
rowSums(res * dict$score)
#[1] 2 -2
This also accounts for when there is multiple matches in a single string:
df <- data.frame(text = c("I love love pandas", "I hate monkeys"))
# run same code as above
#[1] 3 -2