開始使用免費開始

足球場上的 K-means(第 2 部分)

在上一個練習中,你已經成功使用 k-means 演算法,將 lineup 資料框中的兩支球隊分群。這次,我們來看看把 k 設為 3 會發生什麼事。

你會發現演算法依然可以執行,但在這個情境下,這樣做是否合理呢……

本練習屬於課程

R 的叢集分析

檢視課程

練習說明

  • 使用 kmeans() 並設定 centers = 3,為 lineup 資料建立名為 model_km3 的 k-means 模型。
  • 從模型中擷取叢集指定向量 model_km3$cluster,並將其存到變數 clust_km3
  • 將叢集指定加入為欄位 cluster,附加到 lineup 資料框,並將結果存成新的資料框 lineup_km3
  • 使用 ggplot 繪製每位球員在場上的位置,並依叢集著色。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Build a kmeans model
model_km3 <- ___

# Extract the cluster assignment vector from the kmeans model
clust_km3 <- ___

# Create a new data frame appending the cluster assignment
lineup_km3 <- ___

# Plot the positions of the players and color them using their cluster
ggplot(___, aes(x = ___, y = ___, color = factor(___))) +
  geom_point()
編輯並執行程式碼