开始使用免费开始使用

在足球场上进行 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()
编辑并运行代码