開始使用免費開始

階層式分群:探索前的準備

你已經為 oes 資料建立了可能的分群。在使用 ggplot2 探索這些叢集之前,你需要先把 oes 資料矩陣整理成整齊(tidy)的資料框,並為每個職業指派其叢集。

本練習屬於課程

R 的叢集分析

檢視課程

練習說明

  • oes data.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" )
編輯並執行程式碼