文本挖掘错误:"replacement has length zero" & "number of items to replace is not a multiple of replacement length"

Error in text mining: "replacement has length zero" & "number of items to replace is not a multiple of replacement length"

我正在尝试使用 for 循环从文本中提取多个单词。

下面的代码行给我一个错误,显示 replacement has length zeronumber of items to replace is not a multiple of replacement length。为了弄清楚我的问题,请考虑以下情况。

library(tm)
library(stringr)
library(stringi)
mydata<-data.frame(id=c(1,2,3), 
          text=c("This is text mining exercise","Text analysis is bit confusing","Hint on this text 
          analysis?")) 
multiwords<-c("text","analysis","bit confusing")
txt<- freq<- list() 
for(i in 1:length(mydata$id)){ 
    txt[i]<-str_extract_all(mydata[i,], paste0(multiwords,collapse = "|")) freq[i]<-table(txt[i])
}

请注意,multiwords 中的每个术语不一定出现在每次迭代中。

如果我们需要在整个提取的元素上使用 table,请在将 'multiwords' 粘贴为 pattern 后在 'text' 列上使用 str_extract_all,然后unlist list 并得到 table

library(stringr)
lst1 <- str_extract_all(mydata$text, str_c(multiwords, collapse="|"))
table(unlist(lst1))
#    analysis bit confusing          text 
#           2             1             2 

如果我们需要在 list

的每个元素上应用 table
lapply(lst1, table)
#[[1]]

#text 
#   1 

#[[2]]

#     analysis bit confusing 
#            1             1 

#[[3]]

#analysis     text 
#       1        1