You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R语言K-means算法计算观测值到各聚类中心的欧氏距离

解决方案

先运行你提供的聚类代码:

data(mtcars)
k <- kmeans(mtcars, 4)

接下来可以通过以下代码给mtcars新增4列距离数据:

# 计算每个观测到4个聚类中心的欧氏距离
distance_matrix <- sapply(1:nrow(k$centers), function(center_idx) {
  apply(mtcars, 1, function(row) {
    sqrt(sum((row - k$centers[center_idx, ])^2))
  })
})

# 为距离列设置清晰的名称
colnames(distance_matrix) <- paste("dist_to_center", 1:4, sep = "_")

# 将距离列合并到原数据框
mtcars_updated <- cbind(mtcars, distance_matrix)

代码说明

  • sapply循环遍历4个聚类中心,对每个中心计算所有观测的距离
  • apply(mtcars, 1, ...)逐行处理mtcars数据,用欧氏距离公式sqrt(sum((行向量 - 中心向量)^2))计算距离
  • 最后通过cbind把生成的距离列合并到原数据框,得到包含距离信息的新数据框mtcars_updated

内容的提问来源于stack exchange,提问作者Amc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:20:40