我有以下几点:
text <- c('I am a human','It is an animal and not a human, I am a human','Cant think of something else to write','and and is am')
words <- c('and','am','is')我想数一数课文中出现的这些词的总和。因此,输出应该如下:
[1] 1 3 0 4我使用的代码显然不是最优雅的:
TotalCount <- vector(mode='integer',length = 4)
for (ii in 1:4){
for(jj in 1:3){
wordCount <- str_count(text[ii],words[jj])
TotalCount[ii] <- wordCount + TotalCount[ii]
}
}有没有一种更有效率、更优雅和更好的方法来做到这一点?
发布于 2015-10-11 12:53:10
您可以从str_count库中使用stringr函数。
library(stringr)
text <- c('I am a human','It is an animal and not a human, I am a human','Cant think of something else to write','and and is am')
words <- c('and','am','is')
str_count(text, paste(words, collapse="|"))
# [1] 1 3 0 4或
str_count(text, paste0(c("\\b("),paste(words,collapse="|"),c(")\\b")))https://stackoverflow.com/questions/33065147
复制相似问题