-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchapter_09.html
More file actions
1299 lines (1131 loc) · 49.1 KB
/
chapter_09.html
File metadata and controls
1299 lines (1131 loc) · 49.1 KB
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Chapter 9</title>
<script src="site_libs/header-attrs-2.24/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cosmo.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/jqueryui-1.13.2/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-6.4.2/css/all.min.css" rel="stylesheet" />
<link href="site_libs/font-awesome-6.4.2/css/v4-shims.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<script defer src="https://use.fontawesome.com/releases/v5.0.3/js/all.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.0/js/v4-shims.js"></script>
<!-- Global site tag (gtag.js) - Google Analytics
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-151578452-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-151578452-1');
</script>
-->
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-bs-toggle="collapse" data-target="#navbar" data-bs-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">FDA with R</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="about_authors.html">About the Authors</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Datasets
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="dataset_nhanes.html">NHANES</a>
</li>
<li>
<a href="dataset_covid19.html">COVID-19</a>
</li>
<li>
<a href="dataset_cd4.html">CD4</a>
</li>
<li>
<a href="dataset_content.html">Content</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Chapters
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="chapter_01.html">Chapter 1</a>
</li>
<li>
<a href="chapter_02.html">Chapter 2</a>
</li>
<li>
<a href="chapter_03.html">Chapter 3: FPCA</a>
</li>
<li>
<a href="chapter_04.html">Chapter 4: SoFR</a>
</li>
<li>
<a href="chapter_05.html">Chapter 5: FoSR</a>
</li>
<li>
<a href="chapter_06.html">Chapter 6: FoFR</a>
</li>
<li>
<a href="chapter_07.html">Chapter 7</a>
</li>
<li>
<a href="chapter_08.html">Chapter 8</a>
</li>
<li>
<a href="chapter_09.html">Chapter 9</a>
</li>
</ul>
</li>
<li>
<a href="scripts.html">Scripts</a>
</li>
<li>
<a href="https://github.com/FDAwithR">
<span class="fa fa-github"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Chapter 9</h1>
</div>
<p>This document contains clustering approaches for functional data and
it is applied to the US Covid-19 weekly all-cause excess mortality data,
simulated data with noise, CD4 counts after using smoothing, and NHANES
data.</p>
<div id="us-all-cause-excess-and-covid-19-mortality"
class="section level2">
<h2>US all-cause excess and Covid-19 mortality</h2>
<p>Read the COVID-19 data from <code>refund</code> package.</p>
<pre class="r"><code>#Load packages
library(refund)
library(fields)</code></pre>
<p>Extract the necessary information from the data list. Give variables
shorter names.</p>
<pre class="r"><code>CV19 <- COVID19
#Date indicating weeks from the beginning of 2020
current_date <- CV19$US_weekly_excess_mort_2020_dates
#Names of states and territories considered in the analysis
new_states <- CV19$US_states_names
#Excess mortality as a function of time and state
Wd <- CV19$States_excess_mortality_per_million
#Columns are weeks, rows are states
colnames(Wd) <- 1:52
#Population of states
pop_state_n <- CV19$US_states_population
names(pop_state_n) <- new_states</code></pre>
<p>The data we are interested in is stored in <code>Wd</code>. Each row
in this data matrix corresponds to a state or territory (District of
Columbia and Puerto Rico). Every column contains the weekly all-cause
excess death rate per one million residents since the beginning of 2020.
So, the data matrix is <span class="math inline">\(52\times 52\)</span>
dimensional because there are <span class="math inline">\(50\)</span>
states and <span class="math inline">\(2\)</span> teritories (Puerto
Rico and District of Columbia) and <span
class="math inline">\(52\)</span> weeks.</p>
<div id="exploratory-plots-and-analyses" class="section level3">
<h3>Exploratory plots and analyses</h3>
<p>Make a plot of weekly number of excess deaths comparing 2020 with
2019 for each state. Each line corresponds to a state and some states
are emphasized using color: New Jersey (green), Louisiana (red),
California (plum), Maryland (dark blue), and Texas (salmon). The x-axis
corresponds to 52 weeks starting with (the week ending) on January 4,
2020 and ending with (the week ending) on December 26, 2020. The y-axis
is expressed in all-case excess mortality rate per one million
residents.</p>
<pre class="r"><code>par(mfrow = c(1, 1))
cmar <- c(4, 4, 1, 1)
par(mar = cmar)
for(i in 1:length(new_states)){
ylabel = paste("US states weekly excess deaths/million")
xlabel = paste("Weeks starting January 2020")
#Plot only for first state. For others add lines
if(i == 1){
par(bg = "white")
#Here plot the date versus cumulative excess mortality (hence the cumsum)
plot(current_date, Wd[i,], type = "l", lwd = 1.5,
col = rgb(0, 0, 0, alpha = 0.1), cex = 1, xlab = xlabel,
ylab = ylabel, ylim = c(-50, 400), bty = "n")
}
else
{lines(current_date, Wd[i,], lwd = 1, col = rgb(0, 0, 0, alpha = 0.1))}
}
emphasize <- c("New Jersey", "Louisiana", "California", "Maryland", "Texas")
col_emph <- c("darkseagreen3", "red", "plum3", "deepskyblue4", "salmon")
emph_state_ind <- match(emphasize, new_states)
for(i in 1:length(emphasize)){
lines(current_date, Wd[emph_state_ind[i],], lwd = 2.5, col = col_emph[i])
}</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-3-1.png" width="90%" /></p>
<p>Plot the weekly mortality for each state (each dot represents a
state). Each panel corresponds to a specific week on the x-axis and
another specific week on the y-axis. This plot will be improved using
code from Andrew.</p>
<pre class="r"><code>par(mfrow = c(4, 4))
cmar <- c(3, 3, 0, 0)
par(mar = cmar)
plot(Wd[,10], Wd[,20], pch = 19, col = "blue", cex = .7, bty = "n", xlim = c(-40, 150),
ylim = c(-40, 150), main = "", xlab = "Week 10", ylab = "", axes = "FALSE")
mtext("Week 20", side = 2, cex = 0.5, line = 1.7)
axis(side = 2, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.7, tck = -0.1)
plot(0, type = 'n', axes = FALSE, ann = FALSE)
plot(0, type = 'n', axes = FALSE, ann = FALSE)
plot(0, type = 'n', axes = FALSE, ann = FALSE)
plot(Wd[,10], Wd[,30], pch = 19, col = "blue", cex = .7, bty = "n", xlim = c(-40, 150), ylim = c(-40, 150), axes = "FALSE")
axis(side = 2, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.8, tck = -0.1)
mtext("Week 30", side = 2, cex = 0.5, line = 1.7)
plot(Wd[,20], Wd[,30], pch = 19, col = "blue", cex = .7, bty = "n", xlim = c(-40, 150), ylim = c(-40, 150), axes = "FALSE")
plot(0, type = 'n', axes = FALSE, ann = FALSE)
plot(0, type = 'n', axes = FALSE, ann = FALSE)
plot(Wd[,10], Wd[,40], pch = 19, col = "blue", cex = .7, bty = "n", xlim = c(-40, 150), ylim = c(-40, 150), axes = "FALSE")
axis(side = 2, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.8, tck = -0.1)
mtext("Week 40", side = 2, cex = 0.5, line = 1.7)
plot(Wd[,20], Wd[,40], pch = 19, col = "blue", cex = .7, bty = "n", xlim = c(-40, 150), ylim = c(-40, 150), axes = "FALSE")
plot(Wd[,30], Wd[,40], pch = 19, col = "blue", cex = .7, bty = "n", xlim = c(-40, 150), ylim = c(-40, 150), axes = "FALSE")
plot(0, type = 'n', axes = FALSE, ann = FALSE)
plot(Wd[,10], Wd[,50], pch = 19, col = "blue", xlim = c(-40, 150), ylim = c(-40, 150), cex = 0.7, axes = "FALSE")
axis(side = 1, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.8, tck = -0.1)
axis(side = 2, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.8, tck = -0.1)
mtext("Week 10", side = 1, cex = 0.5, line = 1.7)
mtext("Week 50", side = 2, cex = 0.5, line = 1.7)
plot(Wd[,20], Wd[,50], pch = 19, col = "blue", xlim = c(-40, 150), ylim = c(-40, 150), cex = 0.7, axes = "FALSE")
axis(side = 1, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.8, tck = -0.1)
mtext("Week 20", side = 1, cex = 0.5, line = 1.7)
plot(Wd[,30], Wd[,50], pch = 19, col = "blue", xlim = c(-40, 150), ylim = c(-40, 150), cex = 0.7, axes = "FALSE")
axis(side = 1, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.8, tck = -0.1)
mtext("Week 30", side = 1, cex = 0.5, line = 1.7)
plot(Wd[,40], Wd[,50], pch = 19, col = "blue", xlim = c(-40, 150), ylim = c(-40, 150), cex = 0.7, axes = "FALSE")
axis(side = 1, at = c(0, 50, 100), labels = c(0, 50, 100), cex.axis = 0.8, tck = -0.1)
mtext("Week 40", side = 1, cex = 0.5, line = 1.7)</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-4-1.png" width="90%" /></p>
<p>Calculate the mean and median of the excess mortality rate per one
million residents for several weeks across 52 states and territories.
This is used to provide basic summaries and exploratory data analyses to
further investigate the patterns shown in the panels containing
scatterplots of weekly excess mortality rates.</p>
<pre class="r"><code>meanWd10 <- mean(Wd[,10])
medianWd10 <- median(Wd[,10])</code></pre>
<p>There is an average of 3.3 and a median of 2.63 excess deaths per
million in week 10 (week ending on March 7, 2020).</p>
<p>Identify the outlier in week 10 and investigate its properties</p>
<pre class="r"><code>ind_out <- which.max(Wd[,10])
state_out <- new_states[ind_out]
val_out <- round(Wd[ind_out, 6:14], digits = 1)</code></pre>
<p>The outlier observed on week 10 is North Dakota with 10.5, -17, 49.7,
10.5, 70.6, 39.2, 6.5, -30.1, -41.8 excess mortality on weeks <span
class="math inline">\(6\)</span> through <span
class="math inline">\(14\)</span> from the beginning of the year.</p>
<p>Identify the top <span class="math inline">\(5\)</span> states that
on week <span class="math inline">\(20\)</span> have the largest weekly
excess mortality rate.</p>
<pre class="r"><code>topweek20 <- round(Wd[order(Wd[,20])[48:52],20], digits = 1)
states_top_20 <- new_states[order(Wd[,20])[48:52]]</code></pre>
<p>The five states with the highest excess mortality rate for week 20
are New Jersey, Connecticut, Delaware, Massachusetts, District of
Columbia with 104.5, 106.3, 114.5, 122.1, 136.1 excess mortality rate
per one million residents, respectively.</p>
<p>Identify the top <span class="math inline">\(5\)</span> states that
on week <span class="math inline">\(30\)</span> have the largest weekly
excess mortality rate.</p>
<pre class="r"><code>topweek30 <- round(Wd[order(Wd[,30])[48:52],30], digits = 1)
states_top_30 <- new_states[order(Wd[,30])[48:52]]</code></pre>
<p>The five states with the highest excess mortality rate for week 20
were South Carolina, Louisiana, Texas, Arizona, Mississippi with 84.7,
87, 88.8, 107, 119.3 excess mortality rate per one million residents,
respectively.</p>
<p>Identify the top <span class="math inline">\(5\)</span> states that
on week <span class="math inline">\(40\)</span> have the largest weekly
excess mortality rate.</p>
<pre class="r"><code>topweek40 <- round(Wd[order(Wd[,40])[48:52],40], digits = 1)
states_top_40 <- new_states[order(Wd[,40])[48:52]]</code></pre>
<p>The five states with the highest excess mortality rate for week 20
were Wyoming, Missouri, District of Columbia, Arkansas, North Dakota
with 53.2, 58.4, 58.9, 72.3, 75.8 excess mortality rate per one million
residents, respectively.</p>
</div>
<div id="k-means-clustering-of-the-functional-data"
class="section level3">
<h3>K-means clustering of the functional data</h3>
<p>We now conduct K-means clustering for the excess mortality rate data.
For now we do not use smoothing or other types of functional approaches.
We treat the rows of matrix <code>Wd</code> (states) as independent
multivariate observations recorded by rows (each row corresponds to a
state).</p>
<pre class="r"><code>rownames(Wd) <- new_states
set.seed(1000)
kmeans_CV19_3 <- kmeans(Wd, centers = 3)
cl_ind <- kmeans_CV19_3$cluster
cl_cen <- kmeans_CV19_3$centers</code></pre>
<p>Plot (code hidden) the excess mortality rates for each state and
territory as a function of week from the beginning of 2020. Each color
corresponds to a cluster and the thicker lines of the same color
indicate the cluster centers.</p>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-11-1.png" width="90%" /></p>
<p>Make a US map to better indicate the spatial localizaton of the three
clusters estimated by k-means based on the 2020 un-smoothed weekly
excess mortality rates. The code below shows how to produce this type of
map and will be used again for US maps.</p>
<pre class="r"><code>library(usmap)
library(ggplot2)
library(tidyverse)
#Define a color per group
colset <- c(rgb(0.41, 0.05, 0.68), rgb(0, 1, 0), rgb(1, .55, 0))
## load state date which contains FIPS code
data("statepop")
## create a data frame to plot based on the input requirement
state_cluster <- data.frame(full = names(cl_ind), cluster = unname(cl_ind))
data_cluster <- statepop %>%
left_join(state_cluster, by = "full") %>%
select(fips, cluster)
data_cluster$cluster <- as.factor(data_cluster$cluster)
## make the US map
p <- plot_usmap(regions = "states", data = data_cluster, values = "cluster") +
scale_fill_manual(name = "Cluster", values = colset) +
labs(title = "") +
theme(legend.position = "right",
plot.title = element_text(hjust = 0.5, face = "bold"))
print(p)</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-12-1.png" width="90%" /></p>
</div>
<div id="hierarchical-clustering-of-functional-data"
class="section level3">
<h3>Hierarchical clustering of functional data</h3>
<p>Recall that the data are contained in the matrix <code>Wd</code>, a
<span class="math inline">\(52\times 52\)</span> dimensional matrix,
where each state is a row and each column is a week of 2020.</p>
<pre class="r"><code>library(gplots) ##Available from CRAN
library(RColorBrewer)
library(viridis)
library(dendextend)
#Calculate the matrix of distances
dM <- dist(Wd[,]) ^ 2
#Hierarchical clustering on the square Euclidian distances
hc <- hclust(dM, method = "ward.D2")</code></pre>
<p>Plot the dendogram. This code uses the package
<code>dendextend</code>, though better plotting may be available in
other packages. This package allows to color code the dendograms
according to a specific clustering (in our case obtained by cutting the
result of hierarchical clustering to form five clusters).</p>
<pre class="r"><code>#Set the cluster colors (five clusters)
clust.col <- c("#E69A8DFF", "#F6D55C", "#2A9D8F", "#5F4B8BFF", "#ee7600")
#Set the dendogram
hcd <- as.dendrogram(hc)
hcd <- hcd %>%
color_branches(k = 5, col = clust.col) %>%
set("branches_lwd", c(2, 2, 2, 2, 2)) %>%
set("branches_lty", c(1, 1, 1, 1, 1))
cmar <- c(4, 4, 1, 1)
par(mar = cmar)
nodePar <- list(lab.cex = 0.6, pch = NA)
plot(hcd, nodePar = nodePar, axes = FALSE, ylab = "Distance (Ward.D2)",
ylim = c(0, 750000), cex.lab = 0.6)
axis(2, at = c(0, 250000, 500000, 750000),
labels = c("0", "250K", "500K", "750K"), cex.axis = 0.6, lwd = 1)</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-14-1.png" width="90%" /></p>
<p>A complementary way of plotting these results is to display the
heatmap of the data together with the clustering of the rows of the
matrix (states). The clustering re-orders the states (which were
organized in alphabetic order) to match with the hierarchical
clustering. We could have clustered the columns (weeks) as well, but in
this application we are interested in preserving the natural flow of
time. Here we used the function <code>Heatmap</code> in the
<code>R</code> package <code>ComplexHeatmap</code>. Note that the
capital letter H in <code>Heatmap</code> matters! Other functions we
have tried seemed more finicky, but the user is encouraged to try other
packages and heatmap functions.</p>
<pre class="r"><code>par(mfrow = c(1, 1))
par(mar = c(4, 4, 4, 4))
#This package is on Bioconductor but not on Cran
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("ComplexHeatmap")
## Warning: package(s) not installed when version(s) same as or greater than current; use
## `force = TRUE` to re-install: 'ComplexHeatmap'
library(ComplexHeatmap)
library(circlize)
#Set a set of breaks in the colors to account for the large outliers in New Jersey.
breaks <- c(-50, seq(-40, 130, by = 1), 200, 250, 300)
#Often heatmaps can be heavly affected by outliers.
#This requires careful mapping of colors
hmcol <- plasma(length(breaks))
mycol <- colorRamp2(breaks = breaks, col = hmcol)
cmar <- c(4, 4, 1, 1)
par(mar = cmar)
#Plot the heatmap with the row dendogram
Heatmap(Wd, name = "EMR", col = mycol,
row_names_gp = gpar(fontsize = 8),
column_names_gp = gpar(fontsize = 5), cluster_columns = FALSE,
cluster_rows = color_branches(hc, k = 5, col = clust.col))</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-15-1.png" width="90%" /></p>
<p>We want to plot the clusters on the US map. One of the problems is
that clusters are not labeled in increasing order from left to right (as
plotted), but in the sequence in which they are split from the root of
the tree. Thus, we need to relabel clusters to remain consistent with
the left/right presentation of clusters.</p>
<pre class="r"><code>cut_wardd2 <- cutree(hc, k = 5)
loc_cut <- cut_wardd2
loc_cut[cut_wardd2 == 2] <- 1
loc_cut[cut_wardd2 == 5] <- 2
loc_cut[cut_wardd2 == 1] <- 3
loc_cut[cut_wardd2 == 4] <- 4
loc_cut[cut_wardd2 == 3] <- 5
cut_wardd2 <- loc_cut
## load state date which contains FIPS code
data("statepop")
state_cluster <- data.frame(full = names(cut_wardd2), cluster = unname(cut_wardd2))
data_cluster <- statepop %>%
left_join(state_cluster, by = "full") %>%
select(fips, cluster)
data_cluster$cluster <- as.factor(data_cluster$cluster)
## make the US map
p <- plot_usmap(regions = "states", data = data_cluster, values = "cluster") +
scale_fill_manual(name = "Cluster", values = clust.col) +
labs(title = "") +
theme(legend.position = "right",
plot.title = element_text(hjust = 0.5, face = "bold"))
cmar <- c(4, 4, 1, 1)
par(mar = cmar)
print(p)</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-16-1.png" width="90%" /></p>
</div>
<div id="distributional-clustering" class="section level3">
<h3>Distributional clustering</h3>
<p>Distributional clustering is an approach that fits mixtures of
multivariate distributions. The most common approach is mixture of
Gaussian distributions, but t-distributions, spherical distributions
could also be considered. Here we will use the <code>mclust</code>
package, though other packages exist including <code>mixtools</code>,
<code>clusterR</code>, and <code>flexmix</code>.</p>
<pre class="r"><code>#Set the color palette
colset <- c("#E69A8DFF", "#F6D55C", "#2A9D8F", "#5F4B8BFF")
library(mclust)
#Center and scale the data
X <- as.data.frame(apply(Wd, 2, scale))
#Calculate BIC for distributional clustering
BIC <- mclustBIC(X)
#Fit GMM using EM algorithm with 4 clusters suggested by BIC
mod <- Mclust(X, x = BIC)
#Obtain clustering results
res <- mod$classification</code></pre>
<p>Plot the US map of four clusters obtained from the distributional
clustering of the multivariate distributions.</p>
<pre class="r"><code>state_cluster <- data.frame(full = names(cut_wardd2), cluster = res)
data_cluster <- statepop %>%
left_join(state_cluster, by = "full") %>%
select(fips, cluster)
data_cluster$cluster <- as.factor(data_cluster$cluster)
## make the US map
p <- plot_usmap(regions = "states", data = data_cluster, values = "cluster") +
scale_fill_manual(name = "Cluster", values = colset) +
labs(title = "") +
theme(legend.position = "right",
plot.title = element_text(hjust = 0.5, face = "bold"))
cmar <- c(4, 4, 1, 1)
par(mar = cmar)
print(p)</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-18-1.png" width="90%" /></p>
</div>
<div id="clustering-functional-data" class="section level3">
<h3>Clustering functional data</h3>
<p>So far we have treated functional data as multivariate data and
simply applied existing clustering techniques. However, there is
something special about functional data. It can be observed with a lot
of noise, which may require some type of smoothing. Smoothing can be
done either directly, function-by-function or by using a smooth
functional PCA approach. Here we explore transforming the data using
functional PCA and then using clustering on: (1) the scores of the
principal components; and (2) the smooth estimators of the functions. We
will use the function <code>fpca.face</code> from the
<code>refund</code> package based on the COVID weekly excess mortality
data.</p>
<p>Conduct functional PCA</p>
<pre class="r"><code>t <- 1:dim(Wd)[2]
#Apply functional PCA using the FACE approach
results <- fpca.face(Y = Wd, Y.pred = Wd, center = TRUE, argvals = t,
knots = 35, pve = 0.99, var = TRUE)
#Obtain the eigenfunctions and eigenvalues
Phi <- results$efunctions
eigenvalues <- results$evalues
#Obtain the estimated covariance and correlation matrices
cov_est <- Phi %*% diag(eigenvalues) %*% t(Phi)
cor_est <- cov2cor(cov_est)
#Obtain the scores and the predicted functions
PC_scores <- results$scores
Pred <- results$Yhat</code></pre>
<pre class="r"><code>#Name to columns and rows of the covariance
colnames(cov_est) <- 1:52
rownames(cov_est) <- 1:52
colnames(cor_est) <- 1:52
rownames(cor_est) <- 1:52</code></pre>
<p>Below we provide a plot of the first three principal components. The
x-axis is time in weeks starting in January 2020.</p>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-21-1.png" width="90%" /></p>
<p>We now conduct clustering of the data using the PC scores. We use the
first three principal components and use K-means with <span
class="math inline">\(3\)</span> clusters. We compare the clustering
based on the raw data with clustering based on the functional PCA
scores.</p>
<pre class="r"><code>rownames(PC_scores) <- new_states
set.seed(1000)
kmeans_CV19_3 <- kmeans(PC_scores[,1:3], centers = 3)
cl_ind_sc <- kmeans_CV19_3$cluster
cl_cen_sc <- kmeans_CV19_3$centers
#This shows that the two approaches to K-means provide identical results
table(cl_ind, cl_ind_sc)
## cl_ind_sc
## cl_ind 1 2 3
## 1 12 0 0
## 2 0 23 0
## 3 0 0 17</code></pre>
<p>Plot the scores on the first three principal components together with
the colors of the clusters. The x-axis are the scores on PC1 and the
y-axis represents the scores on PC2 (top panel) and PC3 (bottom panel),
respectively.</p>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-23-1.png" width="90%" /></p>
<p>Plot the smooth covariance and correlation function estimates</p>
<pre class="r"><code>breaks <- c(seq(-2000, -1000, length.out = 10), seq(-900, 900, length.out = 100),
seq(1000, 2000, length.out = 10))
hmcol <- magma(length(breaks))
mycol <- colorRamp2(breaks = breaks, col = hmcol)
Heatmap(cov_est, col = mycol, name = "Covariance",
row_names_gp = gpar(fontsize = 5),
column_names_gp = gpar(fontsize = 5), cluster_columns = FALSE,
cluster_rows = FALSE)</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-24-1.png" width="90%" /></p>
<pre class="r"><code>
breaks <- c(seq(-0.5, 0, length.out = 200), seq(0.01, 0.9, length.out = 100),
seq(0.91, 1, length.out = 20))
hmcol <- magma(length(breaks))
mycol <- colorRamp2(breaks = breaks, col = hmcol)
Heatmap(cor_est, col = mycol, name = "Correlation",
row_names_gp = gpar(fontsize = 5), column_names_gp = gpar(fontsize = 5),
cluster_columns = FALSE,
cluster_rows = FALSE)</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-24-2.png" width="90%" /></p>
<p>So far, we have shown results based on K-means clustering of PC
scores. However, we can use any other type of clustering. Below we show
how to conduct hierarchical smoothing using the PC scores on the first
11 PCs</p>
<pre class="r"><code>dM <- dist(PC_scores[,1:11]) ^ 2
#Apply hierarchical clustering
hc_sc <- hclust(dM, method = "ward.D2")
cut_wardd2_sc <- cutree(hc_sc, k = 5)</code></pre>
</div>
</div>
<div id="simulations-for-clustering-noisy-functional-data"
class="section level2">
<h2>Simulations for Clustering Noisy Functional Data</h2>
<p>In the COVID-19 excess mortality rate example, there is no difference
between K-means clustering of the raw data or PC scores. The reason for
that is likely that the data has very little noise.</p>
<p>Therefore, it makes a lot of sense to investigate when functional
data analysis may make a difference in the case of clustering. To do
that we build a simple simulation exercise, where the true data has two
clusters. To these data we add different levels of noise and investigate
how clustering approaches compare when we use the raw data and the
principal component scores after functional PCA (FPCA) smoothing.</p>
<p>Define functional data with two clusters. The first cluster contains
constant functions <span
class="math inline">\(f_i\{(j-1)/n\}=-0.2+0.2*(i-1)/n\)</span>, for
<span class="math inline">\(i=1,\ldots,I=101\)</span> and <span
class="math inline">\(j=1,\ldots,J=101\)</span>. Therefore, functions
are observed at an equal grid of points between <span
class="math inline">\([0,1]\)</span>, each function is constant, and
constants increase from <span class="math inline">\(-0.2\)</span> to
<span class="math inline">\(0.2\)</span> in equal increments. The second
cluster contains the functions <span
class="math inline">\(f_i\{(j-1)/n\}=\{0.8+0.4(i-102)/101\}\sin\{2\pi(j-1)/n\}\)</span>
for <span class="math inline">\(i=102,\ldots,202\)</span> and <span
class="math inline">\(j=1,\ldots,J=101\)</span>. These are sinus
functions with various amplitudes from <span
class="math inline">\(0.8\)</span> to <span
class="math inline">\(1.2\)</span> evaluated at the same grid of equally
spaced observations between <span
class="math inline">\([0,1]\)</span>.</p>
<pre class="r"><code>n_dom <- 101
t <- seq(0, 1, length = n_dom)
a <- seq(-0.2, 0.2, length = 101)
b <- seq(0.8, 1.2, length = 101)
cl1 <- matrix(rep(a, each = 101), ncol = 101, byrow = TRUE)
cl2 <- matrix(rep(t, 101), ncol = 101, byrow = TRUE)
cl2 <- diag(b)%*% sin(2*pi*cl2)
true_data <- rbind(cl1, cl2)</code></pre>
<p>Display the true underlying data with corresponding clusters
indicated by red and blue colors.</p>
<pre class="r"><code>par(mar = c(4, 4, 1, 1))
blues <- colorRampPalette(brewer.pal(9, "Blues"))(100)
reds <- colorRampPalette(brewer.pal(9, "Reds"))(100)
plot(t, true_data[1,], ylim = c(-1.5, 1.5), col = reds[25],
type = "l", lwd = 2, xlab = "Time", ylab = "Outcome", bty = "n")
for(i in 1:10){
lines(t, true_data[1 + 10 * i,], col = reds[25 + 7 * i], lwd = 2)
}
for(i in 1:11){
lines(t, true_data[102 + 10 * (i - 1),], col = blues[25 + 7 * (i - 1)], lwd = 2)
}</code></pre>
<p><img src="chapter_09_files/figure-html/unnamed-chunk-27-1.png" width="90%" /></p>
<pre class="r"><code>true_clust <- c(rep(1, 101), rep(2, 101))
cl_kmeans <- kmeans(true_data, centers = 2)
cl_ind <- cl_kmeans$cluster
#Check that K-means can identify the two clusters
table(true_clust, cl_ind)
## cl_ind
## true_clust 1 2
## 1 0 101
## 2 101 0</code></pre>
<p>We now conduct a simulation where we simulate from the model <span
class="math display">\[w_i(t_j)=f_i(t_j)+\sigma\epsilon_{ij}\;,\]</span>
where <span class="math inline">\(t_j=(j-1)/101\)</span>, <span
class="math inline">\(i=1,\ldots,202\)</span>, <span
class="math inline">\(\epsilon_{ij}\)</span> are mutually independent
<span class="math inline">\(N(0,1)\)</span> random variables and <span
class="math inline">\(\sigma\)</span> controls the amount of noise
around the functions. For each sigma we simulate <code>nsim=500</code>
data sets, and use K-means with <span class="math inline">\(2\)</span>
clusters on: (1) the raw simulated data; and (2) on the scores on the
principal components taht explain <span
class="math inline">\(99\)</span>% of the variance after removing the
estimated noise variance.</p>
<pre class="r"><code>#Number of entries in the true data matrix
n <- dim(true_data)[1] * dim(true_data)[2]
#Noise levels
sigmav = c(0, 1, 2, 3, 4, 5, 10)
nsigma = length(sigmav)
#Number of simulations for each sigma
#nsim = 500
#This is used to compile only. Results should be obtained using n = 500 simulations
nsim = 5
#Define the matrices that store missclassification rates
#Each row corresponds to a simulation
#Each column corresponds to a noise level
prop_missclass_raw <- matrix(rep(NA, nsigma * nsim), ncol = nsigma)
prop_missclass_scores <- matrix(rep(NA, nsigma * nsim), ncol = nsigma)
for(i in 1:nsim){ #Begin simulations
for(j in 1:nsigma){ #Begin looping over levels of noise
sigma <- sigmav[j]
#Simulate noisy functional data
sim_noise <- matrix(rnorm(n), ncol = dim(true_data)[2])
sim_data <- true_data+sigma*sim_noise
#Conduct clustering directly on the raw data (signal+noise)
cl_kmeans_raw <- kmeans(sim_data, centers = 2)
cl_ind_raw <- cl_kmeans_raw$cluster
#Conduct clustering on the smooth estimators (scores)
results <- fpca.face(Y = sim_data, Y.pred = sim_data, center = TRUE,
argvals = t, knots = 35, pve = 0.99, var = TRUE)
#Obtain the scores
PC_scores <- results$scores