R语言--23

聚类实例

step1:计算距离dist(x,method="euclidean")
step2: 聚类hclust(d,method="complete")
step3: cutree函数进行分支

> df1
#注意输入的数据框的结构,每行为一个样本,计算样本间两两间的距离
      height weight      BMI
tom      180     75 23.14815
cindy    165     58 21.30395
jimmy    175     72 23.51020
sam      173     68 22.72044
lucy     160     60 23.43750
lily     165     55 20.20202
> d=dist(df1)#计算距离,默认欧式距离法,可以用method指定其他
> d
            tom     cindy     jimmy       sam      Lucy
cindy 22.746452                                        
jimmy  5.842181 17.345534                              
sam    9.908730 12.884349  4.541336                    
lucy  25.001674  5.792412 19.209510 15.281171          
lily  25.172995  3.195973 19.998602 15.470696  7.776138
> h=hclust(d)
#d需要为dist()函数产生的对象,默认complete,可以用method指定其他
> h

Call:
hclust(d = d)

Cluster method   : complete 
Distance         : euclidean 
Number of objects: 6 

> plot(h)#图片展示聚类结果
聚类结果
> cutree(h,k=4)#对聚类结果进行分支,k=4,分成4支
  tom cindy jimmy   sam  Lucy  lily 
    1     2     3     3     4     2 
> rect.hclust(h,k=4)#以图片的形式对聚类结果进行分支
分支结果

分支结果与cutree分支结果一样,对照着看

你可能感兴趣的:(R语言--23)