建立文件-詞項矩陣
希望你在做完這些文字探勘的基本功後還不會太累!以防萬一,我們回到咖啡主題,一邊從咖啡推文建立文件-詞項矩陣,一邊來點 Starbucks 提提神。
從 coffee.csv 檔案開始,我們已經用常見的轉換步驟產生一個乾淨的語料庫 clean_corp。
當你想以每個文件對應到一列時,就會用到文件-詞項矩陣。這在你要比較作者(放在列中),或資料按時間排序而你想保留時間序列時很有用。tm 套件採用的是「simple triplet matrix」類別。不過,經常將 DTM 重新轉為 as.matrix() 的矩陣後,會更容易操作與檢視該物件。
本練習屬於課程
R 的 Bag-of-Words 文本探勘
練習說明
- 將
DocumentTermMatrix()套用到clean_corp,建立coffee_dtm。 - 使用
as.matrix()建立coffee_m,也就是coffee_dtm的矩陣版本。 - 使用
dim()函式在主控台列印coffee_m的維度。/請留意列數與欄數。 - 列印
coffee_m的一個子集:文件(列)第 25 到 35 筆,以及詞項(欄)"star"與"starbucks"。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create the document-term matrix from the corpus
coffee_dtm <- ___
# Print out coffee_dtm data
coffee_dtm
# Convert coffee_dtm to a matrix
coffee_m <- ___
# Print the dimensions of coffee_m
___
# Review a portion of the matrix to get some Starbucks
___[___:___, c("star", "___")]