開始使用免費開始

在足球場上做 K-means

在前一章,你使用 lineup 資料集學習了階層式叢集分析;本章會用相同的資料來學習k-means 叢集分析。 提醒一下,lineup 資料框包含一場 6v6 足球比賽開局時 12 名球員的位置。

就像之前一樣,你知道場上有兩支隊伍,因此可以使用 k = 2 來做 k-means 分析,以判定每位球員分屬哪一隊。

注意,在 kmeans() 函式中,k 需要透過 centers 參數來設定。

本練習屬於課程

R 的叢集分析

檢視課程

練習說明

  • 使用 kmeans() 並設定 centers = 2,為 lineup 資料建立一個名為 model_km2 的 k-means 模型。
  • 從模型中擷取叢集指派向量 model_km2$cluster,並將其存入變數 clust_km2
  • 將叢集指派作為欄位 cluster 加到 lineup 資料框,並把結果儲存到新的資料框 lineup_km2
  • 使用 ggplot 繪製每位球員在場上的位置,並以叢集顏色區分。

動手互動練習

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

# Build a kmeans model
model_km2 <- kmeans(___, centers = ___)

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

# Create a new data frame appending the cluster assignment
lineup_km2 <- mutate(___, cluster = ___)

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