使用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
相关产品推荐
相关产品推荐

