階層型クラスタリング:探索の準備
oes データのクラスタリングが完成しました。ggplot2 でクラスターを探索する前に、oes データ行列を整然とした(tidy)データフレームに変換し、各職業にクラスターを割り当てる必要があります。
この演習はコースの一部です
Rによるクラスター分析
演習の手順
oesデータ行列からdf_oesデータフレームを作成します。このとき、tibbleライブラリのrownames_to_column()を使って行名を列として保持してください。cutree()をh = 100,000で使用して、クラスター割り当てベクトルcut_oesを作成します。- クラスターの割り当てを
cluster列としてdf_oesデータフレームに追加し、結果をclust_oesという新しいデータフレームに保存します。 tidyr()ライブラリのpivot_longer()関数を使ってデータを ggplot2 分析に適した形式に変換し、整形済みのデータフレームをgathered_oesとして保存します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
dist_oes <- dist(oes, method = 'euclidean')
hc_oes <- hclust(dist_oes, method = 'average')
library(tibble)
library(tidyr)
# Use rownames_to_column to move the rownames into a column of the data frame
df_oes <- rownames_to_column(as.data.frame(___), var = 'occupation')
# Create a cluster assignment vector at h = 100,000
cut_oes <- cutree(___, h = ___)
# Generate the segmented oes data frame
clust_oes <- mutate(___, cluster = ___)
# Create a tidy data frame by gathering the year and values into two columns
gathered_oes <- pivot_longer(data = ___,
cols = -c(occupation, cluster),
names_to = "year",
values_to = "mean_salary" )