我有一个包含2个变量的数据框,我想使用clusGap
函数来查找最佳使用的聚类数。此代码具有类似的结果:
library(cluster)
x <- as.vector(runif(100, 0, 1))
y <- as.vector(runif(100, 0, 1))
df <- data.frame(x, y)
gap_stat <- clusGap(df, FUN = kmeans, nstart = n,
K.max = 10, B = 50)
gap_stat
结果:
Clustering Gap statistic ["clusGap"] from call:
clusGap(x = df, FUNcluster = kmeans, K.max = 10, B = 50, nstart = n)
B=50 simulated reference sets, k = 1..10; spaceH0="scaledPCA"
--> Number of clusters (method 'firstSEmax', SE.factor=1): 1
logW E.logW gap SE.sim
[1,] 2.569315 2.584217 0.0149021144 0.03210076
[2,] 2.285049 2.284537 -0.0005116382 0.03231529
[3,] 2.053193 2.033653 -0.0195399122 0.03282376
[4,] 1.839085 1.835590 -0.0034952935 0.03443303
[5,] 1.691219 1.708479 0.0172603348 0.03419994
[6,] 1.585084 1.597277 0.0121935992 0.03440672
[7,] 1.504763 1.496853 -0.0079104306 0.03422321
[8,] 1.416176 1.405903 -0.0102731340 0.03371149
[9,] 1.333721 1.323658 -0.0100626869 0.03245958
[10,] 1.253199 1.250366 -0.0028330498 0.03034140
正如您在第4行中看到的那样,最佳簇数为1.我希望函数有1作为输出。我需要将最佳输出数量作为环境中的对象,例如n
为1。
通常,此类信息直接位于对象内部,如gap_stat$nc
。为了寻找它,str(gap_stat)
通常就足够了。
然而,在这种情况下,上述策略是不够的。但事实上,你可以看到你对输出感兴趣的数量,这意味着print.clusGap
(因为gap_stat
的类是clusGap)将显示如何获得这个数字。因此,检查cluster:::print.clusGap
导致
maxSE(f = gap_stat$Tab[, "gap"], SE.f = gap_stat$Tab[, "SE.sim"])
# [1] 1