開始使用免費開始

使用 tm 找出常見詞彙

現在你已經知道如何建立詞彙-文件矩陣(term-document matrix),以及它的轉置「文件-詞彙矩陣」(document-term matrix)。我們會把它作為分析的基礎。為了方便分析,需要像第 1 章一樣,使用 as.matrix() 把它轉成一般矩陣。

對新建立的矩陣呼叫 rowSums(),即可彙總一段文字中所有出現的詞彙次數。取得 rowSums() 之後,你可以用 decreasing = TRUEsort(),以便聚焦在最常見的詞彙。

最後,你可以用下面的程式碼,替 term_frequency 的前 5 個詞彙畫出 barplot()

barplot(term_frequency[1:5], col = "#C0DE25")

當然,如果你想把圖表客製化得更精彩,也可以去上我們的 ggplot2 課程喔 :)

本練習屬於課程

R 的 Bag-of-Words 文本探勘

檢視課程

練習說明

  • 使用上一章的詞彙-文件矩陣 coffee_tdm,建立矩陣 coffee_m
  • coffee_m 使用 rowSums() 建立 term_frequency
  • term_frequency 以遞減順序排序,並回存到 term_frequency
  • 使用單一方括號(也就是只用一個 [)進行擷取,印出 term_frequency 的前 10 個詞彙。
  • 繪製這些「前 10 名」詞彙的長條圖。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

## coffee_tdm is still loaded in your workspace

# Convert coffee_tdm to a matrix
coffee_m <- ___

# Calculate the row sums of coffee_m
term_frequency <- ___

# Sort term_frequency in decreasing order
term_frequency <- ___

# View the top 10 most common words
___

# Plot a barchart of the 10 most common words
___(___, col = "tan", las = 2)
編輯並執行程式碼