Hierarchical Clustering: เตรียมข้อมูลสำหรับการสำรวจ
ตอนนี้ได้สร้างการจัดกลุ่มที่เป็นไปได้สำหรับข้อมูล oes แล้ว ก่อนที่จะสำรวจกลุ่มเหล่านี้ด้วย ggplot2 จะต้องแปลง data matrix ของ oes ให้เป็น data frame แบบ tidy โดยกำหนดกลุ่มให้กับแต่ละอาชีพด้วย
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การวิเคราะห์กลุ่มข้อมูลใน R
คำแนะนำการฝึกหัด
- สร้าง data frame
df_oesจาก data.matrix ของoesโดยเก็บชื่อแถว (rowname) ไว้เป็นคอลัมน์ (ใช้rownames_to_column()จากไลบรารีtibble) - สร้างเวกเตอร์การกำหนดกลุ่ม
cut_oesโดยใช้cutree()กำหนดh = 100,000 - เพิ่มผลการกำหนดกลุ่มเป็นคอลัมน์
clusterใน data framedf_oesแล้วบันทึกผลลัพธ์ไปยัง data frame ใหม่ชื่อclust_oes - ใช้ฟังก์ชัน
pivot_longer()จากไลบรารีtidyr()เพื่อปรับรูปแบบข้อมูลให้เหมาะสมสำหรับการวิเคราะห์ด้วย ggplot2 แล้วบันทึก data frame ที่ได้เป็น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" )