Phân cụm phân cấp: Chuẩn bị cho khám phá
Bạn đã tạo được một phân cụm tiềm năng cho dữ liệu oes. Trước khi khám phá các cụm này với ggplot2, bạn cần xử lý ma trận dữ liệu oes thành một data frame gọn (tidy), trong đó mỗi nghề nghiệp được gán vào cụm của mình.
Bài tập này là một phần của khóa học
Phân cụm bằng R
Hướng dẫn bài tập
- Tạo data frame
df_oestừ data.matrixoes, nhớ lưu tên hàng thành một cột (dùngrownames_to_column()từ thư việntibble). - Tạo vectơ gán cụm
cut_oesbằngcutree()vớih = 100,000. - Thêm cột gán cụm
clustervào data framedf_oesvà lưu kết quả thành một data frame mới tênclust_oes. - Dùng hàm
pivot_longer()từ thư việntidyr()để biến đổi dữ liệu sang định dạng phù hợp cho phân tích bằng ggplot2 và lưu data frame đã làm gọn làgathered_oes.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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" )