เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

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 frame df_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" )
แก้ไขและรันโค้ด