-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rCh08.html
2072 lines (1896 loc) · 76.2 KB
/
rCh08.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">rm</span>(<span class="dt">list=</span><span class="kw">ls</span>())
<span class="kw">source</span>(<span class="st">'runDir.R'</span>)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(<span class="st">'ggplot2'</span>)
<span class="kw">runDir</span>(<span class="st">'../CodeExamples/c08_Unsupervised_methods'</span>,
<span class="st">'../Protein'</span>,<span class="dt">last=</span><span class="dv">151</span>)</code></pre></div>
<pre><code>[1] "############################### start 136 Tue May 2 20:40:45 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00136_example_8.1_of_section_8.1.2.R"
[1] "##### in directory ../Protein"
> # example 8.1 of section 8.1.2
> # (example 8.1 of section 8.1.2) : Unsupervised methods : Cluster analysis : Preparing the data
> # Title: Reading the protein data
>
> protein <- read.table("protein.txt", sep="\t", header=TRUE)
> summary(protein)
Country RedMeat WhiteMeat Eggs
Albania : 1 Min. : 4.400 Min. : 1.400 Min. :0.500
Austria : 1 1st Qu.: 7.800 1st Qu.: 4.900 1st Qu.:2.700
Belgium : 1 Median : 9.500 Median : 7.800 Median :2.900
Bulgaria : 1 Mean : 9.828 Mean : 7.896 Mean :2.936
Czechoslovakia: 1 3rd Qu.:10.600 3rd Qu.:10.800 3rd Qu.:3.700
Denmark : 1 Max. :18.000 Max. :14.000 Max. :4.700
(Other) :19
Milk Fish Cereals Starch
Min. : 4.90 Min. : 0.200 Min. :18.60 Min. :0.600
1st Qu.:11.10 1st Qu.: 2.100 1st Qu.:24.30 1st Qu.:3.100
Median :17.60 Median : 3.400 Median :28.00 Median :4.700
Mean :17.11 Mean : 4.284 Mean :32.25 Mean :4.276
3rd Qu.:23.30 3rd Qu.: 5.800 3rd Qu.:40.10 3rd Qu.:5.700
Max. :33.70 Max. :14.200 Max. :56.70 Max. :6.500
Nuts Fr.Veg
Min. :0.700 Min. :1.400
1st Qu.:1.500 1st Qu.:2.900
Median :2.400 Median :3.800
Mean :3.072 Mean :4.136
3rd Qu.:4.700 3rd Qu.:4.900
Max. :7.800 Max. :7.900
> ## Country RedMeat WhiteMeat Eggs
> ## Albania : 1 Min. : 4.400 Min. : 1.400 Min. :0.500
> ## Austria : 1 1st Qu.: 7.800 1st Qu.: 4.900 1st Qu.:2.700
> ## Belgium : 1 Median : 9.500 Median : 7.800 Median :2.900
> ## Bulgaria : 1 Mean : 9.828 Mean : 7.896 Mean :2.936
> ## Czechoslovakia: 1 3rd Qu.:10.600 3rd Qu.:10.800 3rd Qu.:3.700
> ## Denmark : 1 Max. :18.000 Max. :14.000 Max. :4.700
> ## (Other) :19
> ## Milk Fish Cereals Starch
> ## Min. : 4.90 Min. : 0.200 Min. :18.60 Min. :0.600
> ## 1st Qu.:11.10 1st Qu.: 2.100 1st Qu.:24.30 1st Qu.:3.100
> ## Median :17.60 Median : 3.400 Median :28.00 Median :4.700
> ## Mean :17.11 Mean : 4.284 Mean :32.25 Mean :4.276
> ## 3rd Qu.:23.30 3rd Qu.: 5.800 3rd Qu.:40.10 3rd Qu.:5.700
> ## Max. :33.70 Max. :14.200 Max. :56.70 Max. :6.500
> ##
> ## Nuts Fr.Veg
> ## Min. :0.700 Min. :1.400
> ## 1st Qu.:1.500 1st Qu.:2.900
> ## Median :2.400 Median :3.800
> ## Mean :3.072 Mean :4.136
> ## 3rd Qu.:4.700 3rd Qu.:4.900
> ## Max. :7.800 Max. :7.900
>
[1] "############################### end 136 Tue May 2 20:40:45 2017"
[1] "############################### start 137 Tue May 2 20:40:45 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00137_example_8.2_of_section_8.1.2.R"
[1] "##### in directory ../Protein"
> # example 8.2 of section 8.1.2
> # (example 8.2 of section 8.1.2) : Unsupervised methods : Cluster analysis : Preparing the data
> # Title: Rescaling the dataset
>
> vars.to.use <- colnames(protein)[-1] # Note: 1
> pmatrix <- scale(protein[,vars.to.use]) # Note: 2
> pcenter <- attr(pmatrix, "scaled:center") # Note: 3
> pscale <- attr(pmatrix, "scaled:scale")
> attr(pmatrix, "scaled:center") <- NULL
> attr(pmatrix, "scaled:scale") <- NULL
> # Note 1:
> # Use all the columns except the first
> # (Country).
>
> # Note 2:
> # The output of scale() is a matrix. For the
> # purposes of this chapter, you can think of a
> # matrix as a data frame with all numeric columns
> # (this isn’t strictly true, but it’s close enough).
>
> # Note 3:
> # The scale() function annotates its output
> # with two attributes—scaled:center returns the mean
> # values of all the columns, and scaled:scale
> # returns the standard deviations. You’ll store
> # these away so you can “unscale” the data
> # later.
>
[1] "############################### end 137 Tue May 2 20:40:45 2017"
[1] "############################### start 138 Tue May 2 20:40:45 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00138_example_8.3_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # example 8.3 of section 8.1.3
> # (example 8.3 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
> # Title: Hierarchical clustering
>
> d <- dist(pmatrix, method="euclidean") # Note: 1
> pfit <- hclust(d, method="ward.D") # Note: 2
> plot(pfit, labels=protein$Country) # Note: 3</code></pre>
<div class="figure">
<img src="rCh08_files/figure-markdown_github/ch8ex1-1.png" alt="" />
</div>
<pre><code>> # Note 1:
> # Create the distance matrix.
>
> # Note 2:
> # Do the clustering.
>
> # Note 3:
> # Plot the dendrogram.
>
[1] "############################### end 138 Tue May 2 20:40:45 2017"
[1] "############################### start 139 Tue May 2 20:40:45 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00139_informalexample_8.5_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # informalexample 8.5 of section 8.1.3
> # (informalexample 8.5 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
>
> rect.hclust(pfit, k=5)
[1] "############################### end 139 Tue May 2 20:40:45 2017"
[1] "############################### start 140 Tue May 2 20:40:45 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00140_example_8.4_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # example 8.4 of section 8.1.3
> # (example 8.4 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
> # Title: Extracting the clusters found by hclust()
>
> groups <- cutree(pfit, k=5)
> print_clusters <- function(labels, k) { # Note: 1
for(i in 1:k) {
print(paste("cluster", i))
print(protein[labels==i,c("Country","RedMeat","Fish","Fr.Veg")])
}
}
> print_clusters(groups, 5)
[1] "cluster 1"
Country RedMeat Fish Fr.Veg
1 Albania 10.1 0.2 1.7
4 Bulgaria 7.8 1.2 4.2
18 Romania 6.2 1.0 2.8
25 Yugoslavia 4.4 0.6 3.2
[1] "cluster 2"
Country RedMeat Fish Fr.Veg
2 Austria 8.9 2.1 4.3
3 Belgium 13.5 4.5 4.0
9 France 18.0 5.7 6.5
12 Ireland 13.9 2.2 2.9
14 Netherlands 9.5 2.5 3.7
21 Switzerland 13.1 2.3 4.9
22 UK 17.4 4.3 3.3
24 W Germany 11.4 3.4 3.8
[1] "cluster 3"
Country RedMeat Fish Fr.Veg
5 Czechoslovakia 9.7 2.0 4.0
7 E Germany 8.4 5.4 3.6
11 Hungary 5.3 0.3 4.2
16 Poland 6.9 3.0 6.6
23 USSR 9.3 3.0 2.9
[1] "cluster 4"
Country RedMeat Fish Fr.Veg
6 Denmark 10.6 9.9 2.4
8 Finland 9.5 5.8 1.4
15 Norway 9.4 9.7 2.7
20 Sweden 9.9 7.5 2.0
[1] "cluster 5"
Country RedMeat Fish Fr.Veg
10 Greece 10.2 5.9 6.5
13 Italy 9.0 3.4 6.7
17 Portugal 6.2 14.2 7.9
19 Spain 7.1 7.0 7.2
> ## [1] "cluster 1"
> ## Country RedMeat Fish Fr.Veg
> ## 1 Albania 10.1 0.2 1.7
> ## 4 Bulgaria 7.8 1.2 4.2
> ## 18 Romania 6.2 1.0 2.8
> ## 25 Yugoslavia 4.4 0.6 3.2
> ## [1] "cluster 2"
> ## Country RedMeat Fish Fr.Veg
> ## 2 Austria 8.9 2.1 4.3
> ## 3 Belgium 13.5 4.5 4.0
> ## 9 France 18.0 5.7 6.5
> ## 12 Ireland 13.9 2.2 2.9
> ## 14 Netherlands 9.5 2.5 3.7
> ## 21 Switzerland 13.1 2.3 4.9
> ## 22 UK 17.4 4.3 3.3
> ## 24 W Germany 11.4 3.4 3.8
> ## [1] "cluster 3"
> ## Country RedMeat Fish Fr.Veg
> ## 5 Czechoslovakia 9.7 2.0 4.0
> ## 7 E Germany 8.4 5.4 3.6
> ## 11 Hungary 5.3 0.3 4.2
> ## 16 Poland 6.9 3.0 6.6
> ## 23 USSR 9.3 3.0 2.9
> ## [1] "cluster 4"
> ## Country RedMeat Fish Fr.Veg
> ## 6 Denmark 10.6 9.9 2.4
> ## 8 Finland 9.5 5.8 1.4
> ## 15 Norway 9.4 9.7 2.7
> ## 20 Sweden 9.9 7.5 2.0
> ## [1] "cluster 5"
> ## Country RedMeat Fish Fr.Veg
> ## 10 Greece 10.2 5.9 6.5
> ## 13 Italy 9.0 3.4 6.7
> ## 17 Portugal 6.2 14.2 7.9
> ## 19 Spain 7.1 7.0 7.2
>
> # Note 1:
> # A convenience function for printing out the
> # countries in each cluster, along with the values
> # for red meat, fish, and fruit/vegetable
> # consumption. We’ll use this function throughout
> # this section. Note that the function is hardcoded
> # for the protein dataset.
>
[1] "############################### end 140 Tue May 2 20:40:45 2017"
[1] "############################### start 141 Tue May 2 20:40:45 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00141_example_8.5_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # example 8.5 of section 8.1.3
> # (example 8.5 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
> # Title: Projecting the clusters on the first two principal components
>
> library(ggplot2)
> princ <- prcomp(pmatrix) # Note: 1
> nComp <- 2
> project <- (pmatrix %*% princ$rotation)[,1:nComp] # Note: 2
> project.plus <- cbind(as.data.frame(project), # Note: 3
cluster=as.factor(groups),
country=protein$Country)
> ggplot(project.plus, aes(x=PC1, y=PC2)) + # Note: 4
geom_point(aes(shape=cluster)) +
geom_text(aes(label=country),
hjust=0, vjust=1)</code></pre>
<div class="figure">
<img src="rCh08_files/figure-markdown_github/ch8ex1-2.png" alt="" />
</div>
<pre><code>> # Note 1:
> # Calculate the principal components of the
> # data.
>
> # Note 2:
> # The predict() function will rotate the data
> # into the space described by the principal
> # components. We only want the projection on the
> # first two axes.
>
> # Note 3:
> # Create a data frame with the transformed
> # data, along with the cluster label and country
> # label of each point.
>
> # Note 4:
> # Plot it.
>
[1] "############################### end 141 Tue May 2 20:40:45 2017"
[1] "############################### start 142 Tue May 2 20:40:45 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00142_example_8.6_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # example 8.6 of section 8.1.3
> # (example 8.6 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
> # Title: Running clusterboot() on the protein data
>
> library(fpc) # Note: 1
> kbest.p<-5 # Note: 2
> cboot.hclust <- clusterboot(pmatrix,clustermethod=hclustCBI, # Note: 3
method="ward.D", k=kbest.p)
boot 1
boot 2
boot 3
boot 4
boot 5
boot 6
boot 7
boot 8
boot 9
boot 10
boot 11
boot 12
boot 13
boot 14
boot 15
boot 16
boot 17
boot 18
boot 19
boot 20
boot 21
boot 22
boot 23
boot 24
boot 25
boot 26
boot 27
boot 28
boot 29
boot 30
boot 31
boot 32
boot 33
boot 34
boot 35
boot 36
boot 37
boot 38
boot 39
boot 40
boot 41
boot 42
boot 43
boot 44
boot 45
boot 46
boot 47
boot 48
boot 49
boot 50
boot 51
boot 52
boot 53
boot 54
boot 55
boot 56
boot 57
boot 58
boot 59
boot 60
boot 61
boot 62
boot 63
boot 64
boot 65
boot 66
boot 67
boot 68
boot 69
boot 70
boot 71
boot 72
boot 73
boot 74
boot 75
boot 76
boot 77
boot 78
boot 79
boot 80
boot 81
boot 82
boot 83
boot 84
boot 85
boot 86
boot 87
boot 88
boot 89
boot 90
boot 91
boot 92
boot 93
boot 94
boot 95
boot 96
boot 97
boot 98
boot 99
boot 100
> summary(cboot.hclust$result) # Note: 4
Length Class Mode
result 7 hclust list
noise 1 -none- logical
nc 1 -none- numeric
clusterlist 5 -none- list
partition 25 -none- numeric
clustermethod 1 -none- character
nccl 1 -none- numeric
> ## Length Class Mode
> ## result 7 hclust list
> ## noise 1 -none- logical
> ## nc 1 -none- numeric
> ## clusterlist 5 -none- list
> ## partition 25 -none- numeric
> ## clustermethod 1 -none- character
> ## nccl 1 -none- numeric
>
> groups<-cboot.hclust$result$partition # Note: 5
> print_clusters(groups, kbest.p) # Note: 6
[1] "cluster 1"
Country RedMeat Fish Fr.Veg
1 Albania 10.1 0.2 1.7
4 Bulgaria 7.8 1.2 4.2
18 Romania 6.2 1.0 2.8
25 Yugoslavia 4.4 0.6 3.2
[1] "cluster 2"
Country RedMeat Fish Fr.Veg
2 Austria 8.9 2.1 4.3
3 Belgium 13.5 4.5 4.0
9 France 18.0 5.7 6.5
12 Ireland 13.9 2.2 2.9
14 Netherlands 9.5 2.5 3.7
21 Switzerland 13.1 2.3 4.9
22 UK 17.4 4.3 3.3
24 W Germany 11.4 3.4 3.8
[1] "cluster 3"
Country RedMeat Fish Fr.Veg
5 Czechoslovakia 9.7 2.0 4.0
7 E Germany 8.4 5.4 3.6
11 Hungary 5.3 0.3 4.2
16 Poland 6.9 3.0 6.6
23 USSR 9.3 3.0 2.9
[1] "cluster 4"
Country RedMeat Fish Fr.Veg
6 Denmark 10.6 9.9 2.4
8 Finland 9.5 5.8 1.4
15 Norway 9.4 9.7 2.7
20 Sweden 9.9 7.5 2.0
[1] "cluster 5"
Country RedMeat Fish Fr.Veg
10 Greece 10.2 5.9 6.5
13 Italy 9.0 3.4 6.7
17 Portugal 6.2 14.2 7.9
19 Spain 7.1 7.0 7.2
> ## [1] "cluster 1"
> ## Country RedMeat Fish Fr.Veg
> ## 1 Albania 10.1 0.2 1.7
> ## 4 Bulgaria 7.8 1.2 4.2
> ## 18 Romania 6.2 1.0 2.8
> ## 25 Yugoslavia 4.4 0.6 3.2
> ## [1] "cluster 2"
> ## Country RedMeat Fish Fr.Veg
> ## 2 Austria 8.9 2.1 4.3
> ## 3 Belgium 13.5 4.5 4.0
> ## 9 France 18.0 5.7 6.5
> ## 12 Ireland 13.9 2.2 2.9
> ## 14 Netherlands 9.5 2.5 3.7
> ## 21 Switzerland 13.1 2.3 4.9
> ## 22 UK 17.4 4.3 3.3
> ## 24 W Germany 11.4 3.4 3.8
> ## [1] "cluster 3"
> ## Country RedMeat Fish Fr.Veg
> ## 5 Czechoslovakia 9.7 2.0 4.0
> ## 7 E Germany 8.4 5.4 3.6
> ## 11 Hungary 5.3 0.3 4.2
> ## 16 Poland 6.9 3.0 6.6
> ## 23 USSR 9.3 3.0 2.9
> ## [1] "cluster 4"
> ## Country RedMeat Fish Fr.Veg
> ## 6 Denmark 10.6 9.9 2.4
> ## 8 Finland 9.5 5.8 1.4
> ## 15 Norway 9.4 9.7 2.7
> ## 20 Sweden 9.9 7.5 2.0
> ## [1] "cluster 5"
> ## Country RedMeat Fish Fr.Veg
> ## 10 Greece 10.2 5.9 6.5
> ## 13 Italy 9.0 3.4 6.7
> ## 17 Portugal 6.2 14.2 7.9
> ## 19 Spain 7.1 7.0 7.2
> cboot.hclust$bootmean # Note: 7
[1] 0.7958333 0.7882421 0.6631746 0.9151190 0.7596667
> ## [1] 0.7905000 0.7990913 0.6173056 0.9312857 0.7560000
> cboot.hclust$bootbrd # Note: 8
[1] 23 15 41 11 36
> ## [1] 25 11 47 8 35
>
> # Note 1:
> # Load the fpc package. You may have to
> # install it first. We’ll discuss installing R
> # packages in appendix .
>
> # Note 2:
> # Set the desired number of clusters.
>
> # Note 3:
> # Run clusterboot() with hclust
> # ('clustermethod=hclustCBI') using Ward’s method
> # ('method="ward.D"') and kbest.p clusters
> # ('k=kbest.p'). Return the results in an object
> # called cboot.hclust.
>
> # Note 4:
> # The results of the clustering are in
> # cboot.hclust$result. The output of the hclust()
> # function is in cboot.hclust$result$result.
>
> # Note 5:
> # cboot.hclust$result$partition returns a
> # vector of clusterlabels.
>
> # Note 6:
> # The clusters are the same as those produced
> # by a direct call to hclust().
>
> # Note 7:
> # The vector of cluster stabilities.
>
> # Note 8:
> # The count of how many times each cluster was
> # dissolved. By default clusterboot() runs 100
> # bootstrap iterations.
>
[1] "############################### end 142 Tue May 2 20:40:46 2017"
[1] "############################### start 143 Tue May 2 20:40:46 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00143_example_8.7_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # example 8.7 of section 8.1.3
> # (example 8.7 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
> # Title: Calculating total within sum of squares
>
> sqr_edist <- function(x, y) { # Note: 1
sum((x-y)^2)
}
> wss.cluster <- function(clustermat) { # Note: 2
c0 <- apply(clustermat, 2, FUN=mean) # Note: 3
sum(apply(clustermat, 1, FUN=function(row){sqr_edist(row,c0)})) # Note: 4
}
> wss.total <- function(dmatrix, labels) { # Note: 5
wsstot <- 0
k <- length(unique(labels))
for(i in 1:k)
wsstot <- wsstot + wss.cluster(subset(dmatrix, labels==i)) # Note: 6
wsstot
}
> # Note 1:
> # Function to calculate squared distance
> # between two vectors.
>
> # Note 2:
> # Function to calculate the WSS for a single
> # cluster, which is represented as a matrix (one row
> # for every point).
>
> # Note 3:
> # Calculate the centroid of the cluster (the
> # mean of all the points).
>
> # Note 4:
> # Calculate the squared difference of every
> # point in the cluster from the centroid, and sum
> # all the distances.
>
> # Note 5:
> # Function to compute the total WSS from a set
> # of data points and cluster labels.
>
> # Note 6:
> # Extract each cluster, calculate the
> # cluster’s WSS, and sum all the values.
>
[1] "############################### end 143 Tue May 2 20:40:46 2017"
[1] "############################### start 144 Tue May 2 20:40:46 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00144_example_8.8_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # example 8.8 of section 8.1.3
> # (example 8.8 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
> # Title: The Calinski-Harabasz index
>
> totss <- function(dmatrix) { # Note: 1
grandmean <- apply(dmatrix, 2, FUN=mean)
sum(apply(dmatrix, 1, FUN=function(row){sqr_edist(row, grandmean)}))
}
> ch_criterion <- function(dmatrix, kmax, method="kmeans") { # Note: 2
if(!(method %in% c("kmeans", "hclust"))) {
stop("method must be one of c('kmeans', 'hclust')")
}
npts <- dim(dmatrix)[1] # number of rows.
totss <- totss(dmatrix) # Note: 3
wss <- numeric(kmax)
crit <- numeric(kmax)
wss[1] <- (npts-1)*sum(apply(dmatrix, 2, var)) # Note: 4
for(k in 2:kmax) { # Note: 5
if(method=="kmeans") {
clustering<-kmeans(dmatrix, k, nstart=10, iter.max=100)
wss[k] <- clustering$tot.withinss
}else { # hclust # Note: 6
d <- dist(dmatrix, method="euclidean")
pfit <- hclust(d, method="ward.D")
labels <- cutree(pfit, k=k)
wss[k] <- wss.total(dmatrix, labels)
}
}
bss <- totss - wss # Note: 7
crit.num <- bss/(0:(kmax-1)) # Note: 8
crit.denom <- wss/(npts - 1:kmax) # Note: 9
list(crit = crit.num/crit.denom, wss = wss, totss = totss) # Note: 10
}
> # Note 1:
> # Convenience function to calculate the total
> # sum of squares.
>
> # Note 2:
> # A function to calculate the CH index for a
> # number of clusters from 1 to kmax.
>
> # Note 3:
> # The total sum of squares is independent of
> # the clustering.
>
> # Note 4:
> # Calculate WSS for k=1 (which is really just
> # total sum of squares).
>
> # Note 5:
> # Calculate WSS for k from 2 to kmax. kmeans()
> # returns the total WSS as one of its
> # outputs.
>
> # Note 6:
> # For hclust(), calculate total WSS by
> # hand.
>
> # Note 7:
> # Calculate BSS for k from 1 to kmax.
>
> # Note 8:
> # Normalize BSS by k-1.
>
> # Note 9:
> # Normalize WSS by npts - k.
>
> # Note 10:
> # Return a vector of CH indices and of WSS for
> # k from 1 to kmax. Also return total sum of
> # squares.
>
[1] "############################### end 144 Tue May 2 20:40:46 2017"
[1] "############################### start 145 Tue May 2 20:40:46 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00145_example_8.9_of_section_8.1.3.R"
[1] "##### in directory ../Protein"
> # example 8.9 of section 8.1.3
> # (example 8.9 of section 8.1.3) : Unsupervised methods : Cluster analysis : Hierarchical clustering with hclust
> # Title: Evaluating clusterings with different numbers of clusters
>
> library(reshape2) # Note: 1
> clustcrit <- ch_criterion(pmatrix, 10, method="hclust") # Note: 2
> critframe <- data.frame(k=1:10, ch=scale(clustcrit$crit), # Note: 3
wss=scale(clustcrit$wss))
> critframe <- melt(critframe, id.vars=c("k"), # Note: 4
variable.name="measure",
value.name="score")
> ggplot(critframe, aes(x=k, y=score, color=measure)) + # Note: 5
geom_point(aes(shape=measure)) + geom_line(aes(linetype=measure)) +
scale_x_continuous(breaks=1:10, labels=1:10)
Warning: Removed 1 rows containing missing values (geom_point).
Warning: Removed 1 rows containing missing values (geom_path).</code></pre>
<div class="figure">
<img src="rCh08_files/figure-markdown_github/ch8ex1-3.png" alt="" />
</div>
<pre><code>> # Note 1:
> # Load the reshape2 package (for the melt()
> # function).
>
> # Note 2:
> # Calculate both criteria for 1–10
> # clusters.
>
> # Note 3:
> # Create a data frame with the number of
> # clusters, the CH criterion, and the WSS criterion.
> # We’ll scale both the CH and WSS criteria to
> # similar ranges so that we can plot them both on
> # the same graph.
>
> # Note 4:
> # Use the melt() function to put the data
> # frame in a shape suitable for ggplot
>
> # Note 5:
> # Plot it.
>
[1] "############################### end 145 Tue May 2 20:40:46 2017"
[1] "############################### start 146 Tue May 2 20:40:46 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00146_example_8.10_of_section_8.1.4.R"
[1] "##### in directory ../Protein"
> # example 8.10 of section 8.1.4
> # (example 8.10 of section 8.1.4) : Unsupervised methods : Cluster analysis : The k-means algorithm
> # Title: Running k-means with k=5
>
> pclusters <- kmeans(pmatrix, kbest.p, nstart=100, iter.max=100) # Note: 1
> summary(pclusters) # Note: 2
Length Class Mode
cluster 25 -none- numeric
centers 45 -none- numeric
totss 1 -none- numeric
withinss 5 -none- numeric
tot.withinss 1 -none- numeric
betweenss 1 -none- numeric
size 5 -none- numeric
iter 1 -none- numeric
ifault 1 -none- numeric
> ## Length Class Mode
> ## cluster 25 -none- numeric
> ## centers 45 -none- numeric
> ## totss 1 -none- numeric
> ## withinss 5 -none- numeric
> ## tot.withinss 1 -none- numeric
> ## betweenss 1 -none- numeric
> ## size 5 -none- numeric
>
> pclusters$centers # Note: 3
RedMeat WhiteMeat Eggs Milk Fish Cereals
1 1.011180399 0.7421332 0.94084150 0.5700581 -0.2671539 -0.6877583
2 0.006572897 -0.2290150 0.19147892 1.3458748 1.1582546 -0.8722721
3 -0.570049402 0.5803879 -0.08589708 -0.4604938 -0.4537795 0.3181839
4 -0.807569986 -0.8719354 -1.55330561 -1.0783324 -1.0386379 1.7200335
5 -0.508801956 -1.1088009 -0.41248496 -0.8320414 0.9819154 0.1300253
Starch Nuts Fr.Veg
1 0.2288743 -0.5083895 0.02161979
2 0.1676780 -0.9553392 -1.11480485
3 0.7857609 -0.2679180 0.06873983
4 -1.4234267 0.9961313 -0.64360439
5 -0.1842010 1.3108846 1.62924487
> ## RedMeat WhiteMeat Eggs Milk Fish
> ## 1 -0.807569986 -0.8719354 -1.55330561 -1.0783324 -1.0386379
> ## 2 0.006572897 -0.2290150 0.19147892 1.3458748 1.1582546
> ## 3 -0.570049402 0.5803879 -0.08589708 -0.4604938 -0.4537795
> ## 4 1.011180399 0.7421332 0.94084150 0.5700581 -0.2671539
> ## 5 -0.508801956 -1.1088009 -0.41248496 -0.8320414 0.9819154
> ## Cereals Starch Nuts Fr.Veg
> ## 1 1.7200335 -1.4234267 0.9961313 -0.64360439
> ## 2 -0.8722721 0.1676780 -0.9553392 -1.11480485
> ## 3 0.3181839 0.7857609 -0.2679180 0.06873983
> ## 4 -0.6877583 0.2288743 -0.5083895 0.02161979
> ## 5 0.1300253 -0.1842010 1.3108846 1.62924487
> pclusters$size # Note: 4
[1] 8 4 5 4 4
> ## [1] 4 4 5 8 4
>
> groups <- pclusters$cluster # Note: 5
> print_clusters(groups, kbest.p) # Note: 6
[1] "cluster 1"
Country RedMeat Fish Fr.Veg
2 Austria 8.9 2.1 4.3
3 Belgium 13.5 4.5 4.0
9 France 18.0 5.7 6.5
12 Ireland 13.9 2.2 2.9
14 Netherlands 9.5 2.5 3.7
21 Switzerland 13.1 2.3 4.9
22 UK 17.4 4.3 3.3
24 W Germany 11.4 3.4 3.8
[1] "cluster 2"
Country RedMeat Fish Fr.Veg
6 Denmark 10.6 9.9 2.4
8 Finland 9.5 5.8 1.4
15 Norway 9.4 9.7 2.7
20 Sweden 9.9 7.5 2.0
[1] "cluster 3"
Country RedMeat Fish Fr.Veg
5 Czechoslovakia 9.7 2.0 4.0
7 E Germany 8.4 5.4 3.6
11 Hungary 5.3 0.3 4.2
16 Poland 6.9 3.0 6.6
23 USSR 9.3 3.0 2.9
[1] "cluster 4"
Country RedMeat Fish Fr.Veg
1 Albania 10.1 0.2 1.7
4 Bulgaria 7.8 1.2 4.2
18 Romania 6.2 1.0 2.8
25 Yugoslavia 4.4 0.6 3.2
[1] "cluster 5"
Country RedMeat Fish Fr.Veg
10 Greece 10.2 5.9 6.5
13 Italy 9.0 3.4 6.7
17 Portugal 6.2 14.2 7.9
19 Spain 7.1 7.0 7.2
> ## [1] "cluster 1"
> ## Country RedMeat Fish Fr.Veg
> ## 1 Albania 10.1 0.2 1.7
> ## 4 Bulgaria 7.8 1.2 4.2
> ## 18 Romania 6.2 1.0 2.8
> ## 25 Yugoslavia 4.4 0.6 3.2
> ## [1] "cluster 2"
> ## Country RedMeat Fish Fr.Veg
> ## 6 Denmark 10.6 9.9 2.4
> ## 8 Finland 9.5 5.8 1.4
> ## 15 Norway 9.4 9.7 2.7
> ## 20 Sweden 9.9 7.5 2.0
> ## [1] "cluster 3"
> ## Country RedMeat Fish Fr.Veg
> ## 5 Czechoslovakia 9.7 2.0 4.0
> ## 7 E Germany 8.4 5.4 3.6
> ## 11 Hungary 5.3 0.3 4.2
> ## 16 Poland 6.9 3.0 6.6
> ## 23 USSR 9.3 3.0 2.9
> ## [1] "cluster 4"
> ## Country RedMeat Fish Fr.Veg
> ## 2 Austria 8.9 2.1 4.3
> ## 3 Belgium 13.5 4.5 4.0
> ## 9 France 18.0 5.7 6.5
> ## 12 Ireland 13.9 2.2 2.9
> ## 14 Netherlands 9.5 2.5 3.7
> ## 21 Switzerland 13.1 2.3 4.9
> ## 22 UK 17.4 4.3 3.3
> ## 24 W Germany 11.4 3.4 3.8
> ## [1] "cluster 5"
> ## Country RedMeat Fish Fr.Veg
> ## 10 Greece 10.2 5.9 6.5
> ## 13 Italy 9.0 3.4 6.7
> ## 17 Portugal 6.2 14.2 7.9
> ## 19 Spain 7.1 7.0 7.2
>
> # Note 1:
> # Run kmeans() with five clusters (kbest.p=5),
> # 100 random starts, and 100 maximum iterations per
> # run.
>
> # Note 2:
> # kmeans() returns all the sum of squares
> # measures.
>
> # Note 3:
> # pclusters$centers is a matrix whose rows are
> # the centroids of the clusters. Note that
> # pclusters$centers is in the scaled coordinates,
> # not the original protein coordinates.
>
> # Note 4:
> # pclusters$size returns the number of points
> # in each cluster. Generally (though not always) a
> # good clustering will be fairly well balanced: no
> # extremely small clusters and no extremely large
> # ones.
>
> # Note 5:
> # pclusters$cluster is a vector of cluster
> # labels.
>
> # Note 6:
> # In this case, kmeans() and hclust() returned
> # the same clustering. This won’t always be
> # true.
>
[1] "############################### end 146 Tue May 2 20:40:46 2017"
[1] "############################### start 147 Tue May 2 20:40:46 2017"
[1] "##### running ../CodeExamples/c08_Unsupervised_methods/00147_example_8.11_of_section_8.1.4.R"
[1] "##### in directory ../Protein"
> # example 8.11 of section 8.1.4
> # (example 8.11 of section 8.1.4) : Unsupervised methods : Cluster analysis : The k-means algorithm
> # Title: Plotting cluster criteria
>
> clustering.ch <- kmeansruns(pmatrix, krange=1:10, criterion="ch") # Note: 1
> clustering.ch$bestk # Note: 2
[1] 2
> ## [1] 2
> clustering.asw <- kmeansruns(pmatrix, krange=1:10, criterion="asw") # Note: 3
> clustering.asw$bestk
[1] 3
> ## [1] 3
>
> clustering.ch$crit # Note: 4
[1] 0.000000 14.094814 11.417985 10.418801 10.011797 9.964967 9.861682
[8] 9.412089 9.166676 9.075569
> ## [1] 0.000000 14.094814 11.417985 10.418801 10.011797 9.964967
> ## [7] 9.861682 9.412089 9.166676 9.075569
> clustcrit$crit # Note: 5
[1] NaN 12.215107 10.359587 9.690891 10.011797 9.964967 9.506978
[8] 9.092065 8.822406 8.695065
> ## [1] NaN 12.215107 10.359587 9.690891 10.011797 9.964967
> ## [7] 9.506978 9.092065 8.822406 8.695065
>
> critframe <- data.frame(k=1:10, ch=scale(clustering.ch$crit), # Note: 6
asw=scale(clustering.asw$crit))
> critframe <- melt(critframe, id.vars=c("k"),
variable.name="measure",
value.name="score")
> ggplot(critframe, aes(x=k, y=score, color=measure)) +
geom_point(aes(shape=measure)) + geom_line(aes(linetype=measure)) +
scale_x_continuous(breaks=1:10, labels=1:10)</code></pre>
<div class="figure">
<img src="rCh08_files/figure-markdown_github/ch8ex1-4.png" alt="" />
</div>
<pre><code>> summary(clustering.ch) # Note: 7
Length Class Mode
cluster 25 -none- numeric
centers 18 -none- numeric
totss 1 -none- numeric
withinss 2 -none- numeric
tot.withinss 1 -none- numeric
betweenss 1 -none- numeric
size 2 -none- numeric
iter 1 -none- numeric
ifault 1 -none- numeric
crit 10 -none- numeric
bestk 1 -none- numeric
> ## Length Class Mode
> ## cluster 25 -none- numeric
> ## centers 18 -none- numeric
> ## totss 1 -none- numeric
> ## withinss 2 -none- numeric
> ## tot.withinss 1 -none- numeric
> ## betweenss 1 -none- numeric
> ## size 2 -none- numeric
> ## crit 10 -none- numeric
> ## bestk 1 -none- numeric
>
> # Note 1:
> # Run kmeansruns() from 1–10 clusters, and the
> # CH criterion. By default, kmeansruns() uses 100
> # random starts and 100 maximum iterations per
> # run.
>
> # Note 2:
> # The CH criterion picks two clusters.
>
> # Note 3:
> # Run kmeansruns() from 1–10 clusters, and the
> # average silhouette width criterion. Average
> # silhouette width picks 3 clusters.
>
> # Note 4:
> # The vector of criterion values is called
> # crit.
>
> # Note 5:
> # Compare the CH values for kmeans() and
> # hclust(). They’re not quite the same, because the
> # two algorithms didn’t pick the same
> # clusters.
>
> # Note 6:
> # Plot the values for the two criteria.
>
> # Note 7:
> # kmeansruns() also returns the output of
> # kmeans for k=bestk.
>