階層式分群:探索前的準備
你已經為 oes 資料建立了可能的分群。在使用 ggplot2 探索這些叢集之前,你需要先把 oes 資料矩陣整理成整齊(tidy)的資料框,並為每個職業指派其叢集。
本練習屬於課程
R 的叢集分析
練習說明
- 從
oesdata.matrix 建立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" )