使用 tm 查找高频术语
现在,您已经会创建词-文档矩阵以及其转置(文档-词矩阵),我们将以此为基础做一些分析。为便于分析,需要像第 1 章那样用 as.matrix() 将其转换为普通矩阵。
对新生成的矩阵调用 rowSums() 可以汇总一段文本中使用的所有术语。得到 rowSums() 结果后,您可以用 decreasing = TRUE 调用 sort(),从而聚焦最常见的术语。
最后,您可以用下面的代码为 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)