簡體   English   中英

TM軟件包:UseMethod(“ TermDocumentMatrix”,x)中的錯誤

[英]TM Package: Error in UseMethod(“TermDocumentMatrix”, x)

我想在TM軟件包1上的JSS文章中繪制如圖6所示的術語文檔矩陣。文章鏈接: https : //www.jstatsoft.org/article/view/v025i05

我的語料庫Speach-English.txt在這里: https : //github.com/yushu-liu/speach-english.git

該圖應如下所示:

在此處輸入圖片說明

這是我的代碼:

library(tm)
library(stringr)
library(wordcloud)

text <- paste(readLines("D:/Rdata/speach-English.txt"), collapse = " ")
text_tidy <- gsub(pattern = "\\W",replace=" ",text)
text_tidy2 <- gsub(pattern = "\\d",replace=" ",text_tidy)

text_tidy2 <- tolower(text_tidy2)
text_tidy2 <- removeWords(text_tidy2,stopwords())
text_tidy2 <- gsub(pattern = "\\b[A-z]\\b{1}",replace=" ", text_tidy2 )
text_tidy2 <- stripWhitespace(text_tidy2)

textbag <- str_split(text_tidy2,pattern = "\\s+")
textbag <- unlist(textbag)

tdm <- TermDocumentMatrix(textbag, control = list(removePunctuation = TRUE,
                                                removeNumbers = TRUE,
                                                stopwords = TRUE))

plot(tdm, terms = findFreqTerms(tdm, lowfreq = 6)[1:25], corThreshold = 0.5)

但是出現了一個錯誤:

Error in UseMethod("TermDocumentMatrix", x) : 
  no applicable method for 'TermDocumentMatrix' applied to an object of class "character"

為什么? 謝謝!

問題在於您尚未創建Corpus類的對象,這是需要饋給TermDocumentMatrix()的對象的類型。 請在下面查看如何執行此操作的示例。

我還要指出的另一點是,在您的str_split(text_tidy2,pattern = "\\\\s+")您將文本分成了字母組合(各個術語)。 因此,每個文檔僅獲得一個術語。 從這種結構創建tdm沒有多大意義。 這條線的預期目的是什么? 也許我可以指出您想要的東西。

library(tm)
text <-  readLines("https://raw.githubusercontent.com/yushu-liu/speach-english/master/speach-English.txt")
#first define the type of source you want to use and how it shall be read
x <- VectorSource(text)
#create a corpus object
x <- VCorpus(x)
#feed it to tdm
tdm <- TermDocumentMatrix(x)
tdm
#<<TermDocumentMatrix (terms: 4159, documents: 573)>>
#Non-/sparse entries: 14481/2368626
#Sparsity           : 99%
#Maximal term length: 21
#Weighting          : term frequency (tf)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM