始める無料で始める

tm で頻出語を見る

すでに用語-文書行列(term-document matrix)と、その転置である文書-用語行列(document-term matrix)の作り方を学びました。ここでは、それを分析の土台として使います。分析するには、Chapter 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_mrowSums() を適用し、term_frequency を作成します。
  • term_frequency を降順に並べ替え、結果を同じ term_frequency に代入します。
  • 1つの角かっこ([)による部分選択を使って、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)
コードを編集して実行