-
Notifications
You must be signed in to change notification settings - Fork 3
/
chapter_02.html
1158 lines (1014 loc) · 43.4 KB
/
chapter_02.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Chapter 2</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 2</h1>
</div>
<div id="svd-for-us-excess-mortality" class="section level2">
<h2>SVD for US Excess Mortality</h2>
<pre class="r"><code>#Load packages
library(readxl)
library(dplyr)
library(knitr)
library(formattable)
library(lubridate)
library(tidyr)</code></pre>
<div id="weekly-all-cause-mortality-data" class="section level3">
<h3>Weekly all-cause mortality data</h3>
<p>Here we focus on showing how to conduct SVD and PCA decompositions
based on the cumulative weekly all cause mortality in <span
class="math inline">\(52\)</span> states and territories in the US. For
this we need to upload the processed data available in file
<code>US_mortality.Rdata</code></p>
<pre class="r"><code>library(refund)
data("COVID19")
CV19 <- COVID19
names(CV19)
## [1] "US_weekly_mort" "US_weekly_mort_dates"
## [3] "US_weekly_mort_CV19" "US_weekly_mort_CV19_dates"
## [5] "US_weekly_excess_mort_2020" "US_weekly_excess_mort_2020_dates"
## [7] "US_states_names" "US_states_population"
## [9] "States_excess_mortality" "States_excess_mortality_per_million"
## [11] "States_CV19_mortality" "States_CV19_mortality_per_million"
Wd <- CV19$States_excess_mortality_per_million
current_date <- CV19$US_weekly_excess_mort_2020_dates
new_states <- CV19$US_states_names</code></pre>
</div>
<div id="singular-value-decomposition" class="section level3">
<h3>Singular value decomposition</h3>
<p>This is used to illustrate the singular value decomposition (SVD).
SVD is applied to all-cause cumulative excess mortality data as a
function of the week of 2020. Each row in the data matrix corresponds to
a state or territory (District of Columbia and Puerto Rico). Every
column contains the cumulative weekly number of all-cause excess deaths
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.
We start by downloading the data.</p>
<pre class="r"><code>#Obtain the cumulative excess mortality per million in every stat and territory
Wr <- Wd
for(i in 1:dim(Wd)[1]){
Wr[i,] <- cumsum(Wd[i,])
}</code></pre>
<p>Calculate the mean and the centered data matrix <span
class="math inline">\(W\)</span>.</p>
<pre class="r"><code>#Column mean
mW <- colMeans(Wr)
#Construct a matrix of same dimension as Wr with the mean of Wr on each row
mW_mat <- matrix(rep(mW, each = nrow(Wr)), ncol = ncol(Wr))
#Construct the de-meaned data. The columns of W have mean zero
W <- Wr - mW_mat</code></pre>
</div>
<div id="plot-the-data-and-the-mean" class="section level3">
<h3>Plot the data and the mean</h3>
<p>We start by illustrating the data for each state and territory (gray
solid lines) and the mean (dark red solid lines).</p>
<pre class="r"><code>for(i in 1:length(new_states)){
ylabel <- paste("US states cumulative 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, Wr[i,], type = "l", lwd = 1.5,
col = rgb(0, 0, 0, alpha = 0.1), cex = 1, xlab = xlabel,
ylab = ylabel, ylim = c(-50, 2500), bty = "n")
}else{
lines(current_date, Wr[i,], lwd = 1, col = rgb(0, 0, 0, alpha = 0.1))
}
}
lines(current_date, mW, lwd = 2.5, col = "darkred")</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-5-1.png" width="90%" /></p>
</div>
<div id="display-the-de-meaned-data" class="section level3">
<h3>Display the de-meaned data</h3>
<p>We now show the effect of the subtracting the mean from the original
data. We also emphasize a few states: New Jersey (green), Louisiana
(red), California (plum), Maryland (blue), and Texas (salmon).</p>
<pre class="r"><code>for(i in 1:length(new_states)){
ylabel=paste("US states centered cumulative 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, W[i,], type = "l", lwd = 1.5,
col = rgb(0, 0, 0, alpha = 0.1), cex = 1, xlab = xlabel,
ylab = ylabel, ylim = c(-1500, 1500), bty = "n")
}else{
lines(current_date, W[i,], lwd = 1, col = rgb(0, 0, 0, alpha = 0.1))
}
}
#Emphasize 5 states
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, W[emph_state_ind[i],], lwd = 2.5, col = col_emph[i])
}</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-6-1.png" width="90%" /></p>
<p>Calculate the SVD of <span class="math inline">\(W\)</span>, the
corresponding eigenvalues, <span
class="math inline">\(\lambda_k=d_k^2\)</span>, as well as the
individual and cumulative proportion of variance explained.</p>
<pre class="r"><code>SVDofW <- svd(W)
V <- SVDofW$v
lambda <- SVDofW$d ^ 2
propor_var <- round(100 * lambda / sum(lambda), digits = 1)
cumsum_var <- cumsum(propor_var)</code></pre>
<p>Display the first two right singular vectors</p>
<pre class="r"><code>plot(current_date, V[,1], type = "l", lwd = 2.5,
col = "coral", cex = 1, xlab = xlabel, ylim = c(-0.35, 0.35),
ylab = "Right singular vectors", bty = "n")
lines(current_date, V[,2], lwd = 2.5, col = "coral4")</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-8-1.png" width="90%" /></p>
</div>
<div id="reconstruction-of-the-original-data" class="section level3">
<h3>Reconstruction of the original data</h3>
<p>We will use a rank <span class="math inline">\(K_0=2\)</span>
reconstruction of the original data, which explains <span
class="math inline">\(95.9\)</span>% of the de-meaned data
variability.</p>
<pre class="r"><code>#Set the approximation rank
K0 <- 2
#Reconstruct the de-meaned data using the first K0 right singular vectors
rec <- SVDofW$u[,1:K0] %*% diag(SVDofW$d[1:K0]) %*% t(V[,1:K0])
#Add the mean to the rank K0 approximation of W
WK0 <- mW_mat+rec</code></pre>
</div>
<div id="compare-the-real-and-reconstructed-data"
class="section level3">
<h3>Compare the real and reconstructed data</h3>
<pre class="r"><code>ylabel <- paste("US states cumulative excess deaths/million")
plot(current_date, Wr[emph_state_ind[1],], type = "l", lwd = 2.5,
col = col_emph[1], cex = 1, xlab = xlabel,
ylab = ylabel, ylim = c(-50, 2500), bty = "n")
lines(current_date, WK0[emph_state_ind[1],], lwd = 2.5, col = col_emph[1], lty = 2)
for(i in 2:length(emphasize)){
lines(current_date, Wr[emph_state_ind[i],], lwd = 2.5, col = col_emph[i])
lines(current_date, WK0[emph_state_ind[i],], lwd = 2.5, col = col_emph[i], lty = 2)
}</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-10-1.png" width="90%" /></p>
</div>
<div id="plot-the-scores-on-the-first-and-second-singular-vectors"
class="section level3">
<h3>Plot the scores on the first and second singular vectors</h3>
<pre class="r"><code>U <- SVDofW$u
plot(U[,1], U[,2], pch = 19, cex = 0.8,
xlab = "Scores on first right singular vector",
ylab = "Scores on second right singular vector", bty = "n")
points(U[emph_state_ind, 1], U[emph_state_ind, 2], col = col_emph, pch = 19, cex = 1.5)</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-11-1.png" width="90%" /></p>
</div>
</div>
<div id="penalized-spline-smoothing-in-nhanes" class="section level2">
<h2>Penalized Spline Smoothing in NHANES</h2>
<p>We now show how to do penalized spline smoothing on the NHANES data
set. We provide two smoothing examples: scatter plot smoothing, and
nonparametric regression with standard covariates and multiple
predictors with smooth effects.</p>
<div id="mean-pa-among-deceased-and-alive-individuals"
class="section level3">
<h3>Mean PA Among Deceased and Alive Individuals</h3>
<p>The code below shows how to create a figure demonstrating raw
averages (black dots) and corresponding smooth averages of physical
activity data at every minute of the day in the NHANES study.</p>
<pre class="r"><code>library(mgcv)
library(ggplot2)
library(gridExtra)
#load data
nhanes_mortality <- readRDS("./data/nhanes_fda_with_r.rds")
nhanes_plot <- nhanes_mortality %>% group_by(event) %>% summarise(n = n())
nhanes_plot <- nhanes_plot[which(!is.na(nhanes_plot$event)),]
MIMS_group <- c()
MIMS_day <- list()
for(i in 1:nrow(nhanes_plot)){
SEQN_group <- nhanes_mortality$SEQN[which(nhanes_mortality$event == nhanes_plot$event[i])]
MIMS_group <- rbind(MIMS_group,
colMeans(nhanes_mortality$MIMS[which(nhanes_mortality$SEQN %in% SEQN_group),],
na.rm = TRUE))
}
colnames(MIMS_group) <- 1:1440
nhanes_plot <- data.frame(nhanes_plot, MIMS_group)
#covert to long format to make the plot
nhanes_plot2 <- pivot_longer(nhanes_plot, cols = paste0("X",1:1440), names_to = "minute", values_to = "MIMS")
nhanes_plot2$minute <- as.numeric(str_sub(nhanes_plot2$minute, start = 2))
nhanes_plot2$event <- as.factor(nhanes_plot2$event)
#smooth raw average PA among deceased and alive group, respectively
MIMS_sm <- rep(NA, nrow(nhanes_plot2))
ind_alive <- which(nhanes_plot2$event == 0)
ind_deceased <- which(nhanes_plot2$event == 1)
MIMS_sm[ind_alive] <- gam(nhanes_plot2$MIMS[ind_alive] ~ s(nhanes_plot2$minute[ind_alive], bs = "cc"),
method = "REML")$fitted.values
MIMS_sm[ind_deceased] <- gam(nhanes_plot2$MIMS[ind_deceased] ~ s(nhanes_plot2$minute[ind_deceased], bs = "cc"),
method = "REML")$fitted.values
nhanes_plot2$MIMS_sm <- MIMS_sm
rm(MIMS_sm, ind_alive, ind_deceased)
#make a plot
ggplot() +
theme_classic() +
geom_point(data = nhanes_plot2, aes(x = minute, y = MIMS)) +
geom_line(data = nhanes_plot2, aes(x = minute, y = MIMS_sm, color = event), size = 1.5) +
scale_x_continuous(breaks = c(1,6,12,18,23)*60,
labels = c("01:00","06:00","12:00","18:00","23:00")) +
scale_y_continuous(breaks = c(4,8,12,16), limits = c(0, 16)) +
scale_color_manual(values = c("#FF6A6A", "#00BEFF")) +
guides(color="none") +
labs(x = "Time of Day", y = "MIMS") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-12-1.png" width="90%" /></p>
</div>
<div id="regression-of-mean-pa" class="section level3">
<h3>Regression of Mean PA</h3>
<p>Consider now a slightly more complex model, where the outcome is the
average MIMS for every study participant across all days and all minutes
of the day. The predictors are age, BMI, gender, and poverty-income
ratio (PIR), where the effect of age and BMI is allowed to vary
smoothly. The code below shows how to create Figure 2.7 in the book.</p>
<pre class="r"><code>library(mvtnorm)
nhanes_use <- nhanes_mortality %>%
filter(age > 18 & !is.na(age) & !is.na(BMI) & !is.na(gender) & !is.na(PIR))
nhanes_use$MIMS_mean <- nhanes_use$TMIMS/1440 # obtain average MIMS as the outcome
#fit a gam model
fit_mims <- gam(MIMS_mean ~ s(age, k = 51) + s(BMI, k = 51) + gender + PIR, data = nhanes_use)
plot_fit <- plot(fit_mims, select = 0)
#get qn for joint CI
ind_age <- which(str_detect(colnames(vcov(fit_mims)), "age")) # indices corresponding to age
ind_BMI <- which(str_detect(colnames(vcov(fit_mims)), "BMI"))
#obtain design matrix at specified locations of age and BMI
mat_design <- predict(fit_mims, newdata = data.frame(gender = nhanes_use$gender[1:length(seq(1, 100, 2))],
PIR = nhanes_use$PIR[1:length(seq(1, 100, 2))],
age = plot_fit[[1]]$x[seq(1, 100, 2)],
BMI = plot_fit[[2]]$x[seq(1, 100, 2)]),
type = "lpmatrix")
#obtain covariance matrices at selected locations
cov_age <- mat_design[,ind_age] %*% fit_mims$Vp[ind_age, ind_age] %*% t(mat_design[,ind_age]) # covariance matrix of age
cov_BMI <- mat_design[,ind_BMI] %*% fit_mims$Vp[ind_BMI, ind_BMI] %*% t(mat_design[,ind_BMI]) # covariance matrix of BMI
cov_use <- list(cov_age, cov_BMI)
alpha <- 0.05
qn <- rep(0, length(plot_fit))
#obtain quantiles
for(i in 1:length(qn)){
qn[i] <- qmvnorm(1 - alpha, corr = cov2cor(cov_use[[i]]), tail = "both.tails")$quantile
}
#make a plot
p1 <- ggplot() +
theme_classic() +
geom_point(data = nhanes_use, aes(x = age, y = MIMS_mean), alpha = 0.1, size = 0.5) +
labs(x = "Age (years)", y = "MIMS")
p2 <- ggplot() +
theme_classic() +
geom_point(data = nhanes_use, aes(x = BMI, y = MIMS_mean), alpha = 0.1, size = 0.5) +
labs(x = "BMI", y = "MIMS")
p3 <- ggplot() +
theme_classic() +
labs(x = "Age (years)", y = "f(age)") +
geom_polygon(aes(x = c(plot_fit[[1]]$x, rev(plot_fit[[1]]$x)),
y = c(plot_fit[[1]]$fit + plot_fit[[1]]$se/2*qn[1], rev(plot_fit[[1]]$fit - plot_fit[[1]]$se/2*qn[1]))),
fill = "gray20", alpha = 0.2) +
geom_polygon(aes(x = c(plot_fit[[1]]$x, rev(plot_fit[[1]]$x)),
y = c(plot_fit[[1]]$fit + plot_fit[[1]]$se, rev(plot_fit[[1]]$fit - plot_fit[[1]]$se))),
fill = "gray10", alpha = 0.4) +
geom_line(aes(x = plot_fit[[1]]$x, y = plot_fit[[1]]$fit), lty = 1) +
geom_hline(yintercept = 0, color = "lightgray", alpha = 0.7, lty = 2, lwd = 0.3)
p4 <- ggplot() +
theme_classic() +
labs(x = "BMI", y = "g(BMI)") +
geom_polygon(aes(x = c(plot_fit[[2]]$x, rev(plot_fit[[2]]$x)),
y = c(plot_fit[[2]]$fit + plot_fit[[2]]$se/2*qn[2], rev(plot_fit[[2]]$fit - plot_fit[[2]]$se/2*qn[2]))),
fill = "gray10", alpha = 0.2) +
geom_polygon(aes(x = c(plot_fit[[2]]$x, rev(plot_fit[[2]]$x)),
y = c(plot_fit[[2]]$fit + plot_fit[[2]]$se, rev(plot_fit[[2]]$fit - plot_fit[[2]]$se))),
fill = "gray20", alpha = 0.4) +
geom_line(aes(x = plot_fit[[2]]$x, y = plot_fit[[2]]$fit), lty = 1) +
geom_hline(yintercept = 0, color = "lightgray", alpha = 0.7, lty = 2, lwd = 0.3)
grid.arrange(p1, p2, p3, p4, nrow = 2)</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-13-1.png" width="90%" /></p>
</div>
</div>
<div id="svd-with-noisy-data" class="section level2">
<h2>SVD with noisy data</h2>
<p>Singular value decomposition is a powerful method, but it essentially
assumes that data are observed without error. Even when the truncated
SVD is used as an approximation, this is done because the remaining
variation is small, not because it is important or large. We are now
investigating what happens when SVD is applied, incorrectly, to a data
generating process that contains substantial noise.</p>
<p>Simulate samples of curves from the model <span
class="math display">\[y_{ij}=b_{1i}v_1(j)+b_{2i}v_2(j)+\epsilon_{ij}\;,\]</span>
for <span class="math inline">\(j=1,\ldots,p+1\)</span> where <span
class="math inline">\(\epsilon_{ij}\sim N(0,\sigma^2_\epsilon)\)</span>,
<span class="math inline">\(b_{1i}\sim N(0,\sigma^2_1)\)</span>, and
<span class="math inline">\(b_{2i}\sim N(0,\sigma^2_2)\)</span>. Here
<span class="math inline">\(v_1=x_1/||x_1||\)</span> and <span
class="math inline">\(v_2=x_2/||x_2||\)</span>, where <span
class="math inline">\(x_1(j)=1\)</span> and <span
class="math inline">\(x_2(j)=\frac{j-1}{p}-\frac{1}{2}\)</span>, for
<span class="math inline">\(j=1,\ldots,p+1\)</span>. This ensures that
<span class="math inline">\(v_1\)</span> and <span
class="math inline">\(v_2\)</span> are orthonormal vectors. We use <span
class="math inline">\(p=100\)</span> and generate <span
class="math inline">\(n=150\)</span> samples with <span
class="math inline">\(\sigma^2_1=4\)</span> and <span
class="math inline">\(\sigma^2_1=1\)</span>.</p>
<pre class="r"><code>#setting error variance
sigma2eps <- 1
#setting the means of the random effects
mu <- c(0, 0)
#setting the correlation of random effects
rho <- 0
#setting the random effects variances
sigma11 <- 4
sigma22 <- 1
sigma12 <- rho * sqrt(sigma11 * sigma22)
#build the covariance matrix
Sigma <- matrix(c(sigma11, sigma12, sigma12, sigma22), ncol = 2)</code></pre>
<p>Simulate from the model</p>
<pre class="r"><code>set.seed(5272021)
#grid size
p <- 100
#sample_size
n <- 150
#Define the v1, v2 vectors. They are orthonormal: the sum of squares of their entries = 1
v1 <- rep(1, p + 1)
v1 <- v1 / sqrt(sum(v1 ^ 2))
v2 <- (0:p) / p - 0.5
v2 <- v2 / sqrt(sum(v2 ^ 2))
#This is the matrix design
Z <- cbind(v1, v2)
#Simulate the random effects
b <- mvrnorm(n, mu, Sigma)
#Simulate errors
epsilon <- matrix(rnorm(n * (p + 1), 0, sqrt(sigma2eps)), ncol = n)
#Simulate data
Y <- Z %*% t(b) + epsilon</code></pre>
<p>Apply SVD to the data matrix</p>
<pre class="r"><code>Wr <- t(Y)
mW <- colMeans(Wr)
#Construct a matrix with the mean repeated on each row
mWmat <- matrix(rep(mW, each = nrow(Wr)), ncol = ncol(Wr))
#Center the data
W <- Wr-mWmat
#Calculate the SVD of W
SVDofW <- svd(W)
#Left singular vectors stored by columns
U <- SVDofW$u
#Singular values
d <- SVDofW$d
#Right singular vectors stored by columns
V <- SVDofW$v</code></pre>
<div id="including-plots" class="section level3">
<h3>Including Plots</h3>
<p>Plotting the data. This is used to illustrate how the generated data
look like. In particular, it shows the effect of of noise on linear
trends for each study participant.</p>
<pre class="r"><code>#Plot the first study participant
plot(v2, Y[,1], type = "l", lwd = 2,
col = rgb(0, 0, 0, alpha = 0.1), bty = "n",
ylim = c(min(Y), max(Y)),
xlim = c(min(v2), max(v2)),
xlab = "Covariate", ylab = "Functional outcome")
#Add the data for the other study partcipants. They are all in gray
for(i in 2:dim(Y)[2]){
lines(v2, Y[,i], lwd = 1, col = rgb(0, 0, 0, alpha = 0.1))
}
#Two study participants are highlighted
lines(v2, Y[,1], lwd = 2, col = "cadetblue2")
lines(v2, Y[,100], lwd = 2, col = "salmon")</code></pre>
<p><img src="chapter_02_files/figure-html/pressure-1.png" width="90%" /></p>
<p>Plotting the true and estimated eigenfunctions</p>
<pre class="r"><code>plot(v2, v1, type = "l", lwd = 4, bty = "n",
ylim = c(min(-V[,1:2]), max(-V[,1:2])), xlab = "Covariate", ylab = "Right singular vectors", col = "cadetblue4")
lines(v2, v2, lwd = 4, col = "cadetblue2")
lines(v2, -V[,1], lwd = 2, col = "coral")
lines(v2, -V[,2], lwd = 2, col = "coral4")</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-18-1.png" width="90%" /></p>
<p>Scaled eigenvalues</p>
<pre class="r"><code>round(d[1:5] ^ 2 / n, digits = 3)
## [1] 5.296 3.312 3.071 2.931 2.895</code></pre>
<p>Plot the percent variance explained by each estimated right
eigenvector</p>
<pre class="r"><code>plot(d ^ 2 / sum(d ^ 2), bty = "n",
type = "p", pch = 19, cex = 0.8,
xlab = "Right singular vector number",
ylab = "Percent variance explained")</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-20-1.png" width="90%" /></p>
</div>
</div>
<div id="covariance-smoothing-in-nhanes" class="section level2">
<h2>Covariance Smoothing in NHANES</h2>
<p>We now illustrate covariance smoothing for dense functional data
using the NHANES accelerometry data. The code below creates the
estimated raw covariance and smooth covariance functions.</p>
<pre class="r"><code>library(fields)
#do FPCA on the data to obtain eigenfunctions and eigenvalues
MIMS <- unclass(nhanes_use$MIMS[, seq(10, 1440, 10)])
fit_fpca_0.01 <- fpca.face(Y = MIMS, lambda = 0.01)
fit_fpca_1 <- fpca.face(Y = MIMS, lambda = 1)
fit_fpca_100 <- fpca.face(Y = MIMS, lambda = 100)
#calculate smoothed covariance
cov_unsmoothed <- cov(MIMS, use = "pairwise.complete.obs")
cov_smoothed_0.01 <- tcrossprod(fit_fpca_0.01$efunctions %*% diag(sqrt(fit_fpca_0.01$evalues)))
cov_smoothed_1 <- tcrossprod(fit_fpca_1$efunctions %*% diag(sqrt(fit_fpca_1$evalues)))
cov_smoothed_100 <- tcrossprod(fit_fpca_100$efunctions %*% diag(sqrt(fit_fpca_100$evalues)))
#make a plot
par(mfrow = c(2, 2), mgp=c(2.4,1,0), mar = c(3.5, 4, 3, 3), oma = c(0.5, 0.5, 0, 0))
image.plot(cov_unsmoothed, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = "Unsmoothed", zlim = c(-12, 72), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
image.plot(cov_smoothed_0.01, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = bquote(bold("Smoothed (" ~ lambda ~ "= 0.01)" )),
zlim = c(-12, 72), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
image.plot(cov_smoothed_1, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = bquote(bold("Smoothed (" ~ lambda ~ "= 1)" )),
zlim = c(-12, 72), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
image.plot(cov_smoothed_100, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = bquote(bold("Smoothed (" ~ lambda ~ "= 100)" )),
zlim = c(-12, 72), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
mtext("Time of day", side = 1, line = -1, outer = TRUE)
mtext("Time of day", side = 2, line = -1, outer = TRUE)</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-21-1.png" width="90%" /></p>
<p>Similarly, the code below shows how to calculate smoothed correlation
functions and reproduce Figure 2.12 in the book.</p>
<pre class="r"><code>#calculate smoothed correlation
cor_unsmoothed <- cor(MIMS, use = "pairwise.complete.obs")
cor_smoothed_0.01 <- cov2cor(cov_smoothed_0.01)
cor_smoothed_1 <- cov2cor(cov_smoothed_1)
cor_smoothed_100 <- cov2cor(cov_smoothed_100)
#make a plot
par(mfrow = c(2, 2), mgp=c(2.4,1,0), mar = c(3.5, 4, 3, 3), oma = c(0.5, 0.5, 0, 0))
image.plot(cor_unsmoothed, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = "Unsmoothed", zlim = c(-1, 1), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
image.plot(cor_smoothed_0.01, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = bquote(bold("Smoothed (" ~ lambda ~ "= 0.01)" )), zlim = c(-1, 1), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
image.plot(cor_smoothed_1, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = bquote(bold("Smoothed (" ~ lambda ~ "= 1)" )), zlim = c(-1, 1), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
image.plot(cor_smoothed_100, axes = F,
# xlab = "Time of day", ylab = "Time of day",
main = bquote(bold("Smoothed (" ~ lambda ~ "= 100)" )), zlim = c(-1, 1), legend.mar = 6)
axis(1, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
axis(2, at = c(1, 6, 12, 18, 23)/24, labels = c("01:00", "06:00", "12:00", "18:00", "23:00"))
mtext("Time of day", side = 1, line = -1, outer = TRUE)
mtext("Time of day", side = 2, line = -1, outer = TRUE)</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-22-1.png" width="90%" /></p>
</div>
<div id="covariance-smoothing-for-cd4-counts" class="section level2">
<h2>Covariance Smoothing for CD4 Counts</h2>
<p>This document shows how to visualize the CD4 counts data, its raw and
smooth covariance operators.</p>
<pre class="r"><code>library(refund)
library(face)
library(fields)</code></pre>
<pre class="r"><code>#Load the data
data(cd4)
n <- nrow(cd4)
T <- ncol(cd4)
#Construct a vectorized form of the data
id <- rep(1:n, each = T)
t <- rep(-18:42, times = n)
y <- as.vector(t(cd4))
#Indicator for NA observations. This takes advantage of the sparse nature of the data
sel <- which(is.na(y))
#Organize data as outcome, time, subject ID
data <- data.frame(y = log(y[-sel]), argvals = t[-sel],
subj <- id[-sel])
data <- data[data$y > 4.5,]
#Provide the structure of the transformed data
head(data)
## y argvals subj....id..sel.
## 1 6.306275 -9 1
## 2 6.794587 -3 1
## 3 6.487684 3 1
## 4 6.622736 -3 2
## 5 6.129050 3 2
## 6 5.198497 9 2</code></pre>
<p>Apply the function from the package. This function uses penalized
splines smothing to estimate the covariance and correlation and produce
predictions.</p>
<pre class="r"><code>#Fit FACEs to the CD4 counts data
fit_face <- face.sparse(data, argvals.new = (-20:40))
data.h <- data
tnew <- fit_face$argvals.new</code></pre>
<pre class="r"><code>#Estimated covariance
Cov <- fit_face$Chat.new
#Estimated variance
Cov_diag <- diag(Cov)
#Estimated correlation
Cor <- fit_face$Cor.new</code></pre>
<p>Plot the covariance as a function of time.</p>
<pre class="r"><code>Xlab <- "Months since seroconversion"
Ylab <- "log (CD4 count)"
#Plot the smooth variance estimate
par(mfrow = c(1, 1), mar = c(4.5, 4.5, 3, 2))
plot(tnew, Cov_diag, type="l", xlab = Xlab, ylab = "",
main = "CD4: variance function", cex.axis = 1.25,
cex.lab = 1.25, cex.main = 1.25, lwd = 2)</code></pre>
<p><img src="chapter_02_files/figure-html/unnamed-chunk-27-1.png" width="90%" /></p>
<p>How does one plot the raw covariance and correlation? We build a
matrix of submatrices, each corresponding to one study participant. Each
row of the submatrix corresponding to a study participant, <span
class="math inline">\(i\)</span>, contains (<span
class="math inline">\(j_i\)</span>, <span
class="math inline">\(k_i\)</span>,<span class="math inline">\(r_i
r_j\)</span>), <span class="math inline">\(j_i,k_i=1,\ldots,p_i\)</span>
and <span class="math inline">\(r_i r_j\)</span> is the product of these
residuals.</p>
<pre class="r"><code>#First calculate the matrix of residuals
tcd4 <- log(cd4)