在对我的数据集(名为data.matrix的数据框)执行集群分析后,我在末尾(第 27 列)添加了一个名为cluster的新列,其中包含每个实例所属的集群名称。
我现在想要的是来自每个集群的代表性实例。我试图找到与集群质心欧几里得距离最小的实例(并对我的每个集群重复该过程)
这就是我所做的。你能想到其他——也许更优雅——的方式吗?(假设没有空值的数字列)。
clusters <- levels(data.matrix$cluster)
cluster_col = c(27)
for (j in 1:length(clusters)) {
# get the subset for cluster j
data = data.matrix[data.matrix$cluster == clusters[j],]
# remove the cluster column
data <- data[,-cluster_col]
# calculate the centroid
cent <- mean(data)
# copy data to data.matrix_cl, attaching a distance column at the end
data.matrix_cl <- cbind(data, dist = apply(data, 1, function(x) {sqrt(sum((x - cent)^2))}))
# get instances with min distance
candidates <- data.matrix_cl[data.matrix_cl$dist == min(data.matrix_cl$dist),]
# print their rownames
print(paste("Candidates for cluster ",j))
print(rownames(candidates))
}