层次聚类:探索前的准备
您已经为 oes 数据创建了一个潜在的聚类。在使用 ggplot2 探索这些聚类之前,您需要先将 oes 数据矩阵处理为整洁的数据框,并为每个职业分配其所属的聚类。
本练习是课程的一部分
R 中的聚类分析
练习说明
- 通过
tibble库的rownames_to_column(),从oes数据矩阵创建数据框df_oes,并将行名保存为一列。 - 使用
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" )