【发布时间】:2015-10-16 04:22:55
【问题描述】:
我对 R 很陌生,我想创建一个函数,它需要几个点,找到这些点的中心(比如质心),然后从这些点画出分隔组的线点,该中心位于点的中间。类似于制作馅饼片:我们从中心分割馅饼,得到等量的部分。
我用于查找中心和绘图本身的代码如下:
distance <- function(points1, points2) {
distanceMatrix <- matrix(NA, nrow=dim(points1)[1], ncol=dim(points2)[1])
for(i in 1:nrow(points2)) {
distanceMatrix[,i] <- sqrt(rowSums(t(t(points1)-points2[i,])^2))
}
distanceMatrix
}
find_cluster <- function(x, centers, distFun, nItter=10) {
clusterHistory <- vector(nItter, mode="list")
centerHistory <- vector(nItter, mode="list")
for(i in 1:nItter) {
distsToCenters <- distFun(x, centers)
clusters <- apply(distsToCenters, 1, which.min)
centers <- apply(x, 2, tapply, clusters, mean)
# Saving history
clusterHistory[[i]] <- clusters
centerHistory[[i]] <- centers
}
list(clusters=clusterHistory, centers=centerHistory)
}
a3=as.matrix(test)
centers <- a3[sample(nrow(a3), 5),]
theResult <- find_cluster(a3, centers, myEuclid, 10)
剧情:
plot(a3, col=theResult$clusters[[i]],
main=paste("itteration:", i), xlab="x", ylab="y")
points(theResult$centers[[i]],
cex=1, pch=19, col=1:nrow(theResult$centers[[i]]))
所以函数应该这样做:
- 输入中心
- 找到这些点(即聚类中心)的质心(或质点)
- 从主中心(即质心)开始,绘制线条或多边形,以便将集群分开
【问题讨论】:
标签: r function plot polygon k-means