How would one efficiently count the number of instances of one character string which occur within another character string?
Below is my code to date. It successfully identifies if any instance of the one string occurs in the other string. However, I do not know how to extend it from a TRUE/FALSE relationship to a counting relationship.
x <- ("Hello my name is Christopher. Some people call me Chris")
y <- ("Chris is an interesting person to be around")
z <- ("Because he plays sports and likes statistics")
lll <- tolower(list(x,y,z))
dict <- tolower(c("Chris", "Hell"))
mmm <- matrix(nrow=length(lll), ncol=length(dict), NA)
for (i in 1:length(lll)) {
for (j in 1:length(dict)) {
mmm[i,j] <- sum(grepl(dict[j],lll[i]))
}
}
mmm
It yields:
[,1] [,2]
[1,] 1 1
[2,] 1 0
[3,] 0 0
Since the lower-case string "chris" appears twice in the lll[1]
I would like mmm[1,1]
to be 2 instead of 1.
Real example is much higher dimension...so would love if code could be vectorized instead of using my brute force for loops.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…