-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchapter_05.html
More file actions
1730 lines (1628 loc) · 76.5 KB
/
Copy pathchapter_05.html
File metadata and controls
1730 lines (1628 loc) · 76.5 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 5: FoSR</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 5: FoSR</h1>
</div>
<p>This book Chapter and the code in this page considers functions as
responses in models with scalar predictors. This setting is widespread
in applications of functional data analysis; we will focus on the linear
Function-on-Scalar Regression (FoSR) model.</p>
<div id="motivation-and-exploratory-analysis-of-mims-profiles"
class="section level2">
<h2>Motivation and Exploratory Analysis of MIMS Profiles</h2>
<p>The code below imports and organizes data the processed NHANES data
<code>nhanes_fda_with_r.rds</code> and available <a
href="dataset_nhanes.html">here</a>. This code assumes the data are
stored in the directory <code>./data/</code>. We retain a small number
of scalar covariates (<code>gender</code> and <code>age</code>, as well
as the participant ID in <code>SEQN</code> which we convert to a factor
variable) and create a categorical age variable. Subjects who are
missing covariate information are dropped. To keep the examples in this
section computationally feasible, we use the first 250 subjects in this
dataset.</p>
<pre class="r"><code>nhanes_df =
readRDS(
here::here("data", "nhanes_fda_with_r.rds")) %>%
select(SEQN, gender, age, MIMS_mat = MIMS) %>%
mutate(
age_cat =
cut(age, breaks = c(18, 35, 50, 65, 80),
include.lowest = TRUE),
SEQN = as.factor(SEQN)) %>%
drop_na(age, age_cat) %>%
tibble() %>%
slice(1:250) </code></pre>
<p>In the next code chunk, the <code>MIMS</code> variable is converted
to a <code>tidyfun</code> object and stored as a single column of
functional observations.</p>
<pre class="r"><code>nhanes_df =
nhanes_df %>%
mutate(
MIMS_tf = matrix(MIMS_mat, ncol = 1440),
MIMS_tf = tfd(MIMS_tf, arg = seq(1/60, 24, length = 1440)))</code></pre>
<p>One way to explore the associations between subject-level
characteristics and 24-hour activity is to consider the MIMS profile as
a response that varies according to scalar predictors like age and
gender. The Figure below shows minute-level averages for participants in
each age category, separately for male and female. From this, we observe
a clear diurnal pattern of activity, and note a decrease in physical
activity in the afternoon and evening as age increases this is
particularly noticeable for male participants.</p>
<pre class="r"><code>nhanes_df %>%
group_by(age_cat, gender) %>%
summarize(mean_mims = mean(MIMS_tf)) %>%
ggplot(aes(y = mean_mims, color = age_cat)) +
geom_spaghetti() +
facet_grid(.~gender) +
scale_x_continuous(
breaks = seq(0, 24, length = 5),
labels = str_c(seq(0, 24, length = 5), ":00")) +
labs(x = "Time of day (hours)", y = "Average MIMS")
## `summarise()` has grouped output by 'age_cat'. You can override using the
## `.groups` argument.</code></pre>
<p><img src="chapter_05_files/figure-html/unnamed-chunk-2-1.png" width="90%" /></p>
<p>Exploratory plots like this one are useful for beginning to
understand the effects of covariates on physical activity, but are
limited in their scope; more formal approaches to function-on-scalar
regression adjust for covariates and ensure smoothness across adjacent
time points.</p>
<div id="regressions-using-binned-data" class="section level3">
<h3>Regressions using Binned Data</h3>
<p>To build intuition for functional response model interpretations,
identify practical challenges, and motivate later developments, we fit a
series of regressions to MIMS profiles using binned or aggregate
observations. The next code chunk aggregates minute-level data into
hour-length bins, so that each MIMS profile consists of 24 observations.
To obtain hourly trajectories, we “smooth” minute-level data using a
rolling mean with a 60-minute bandwidth and evaluate the resulting
functions at the midpoint of each hour.</p>
<pre class="r"><code>nhanes_df =
nhanes_df %>%
mutate(
MIMS_hour =
tf_smooth(MIMS_tf, method = "rollmean", k = 60, align = "center"),
MIMS_hour = tfd(MIMS_hour, arg = seq(.5, 23.5, by = 1)))
## setting fill = 'extend' for start/end values.
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `MIMS_hour = tf_smooth(MIMS_tf, method = "rollmean", k = 60,
## align = "center")`.
## Caused by warning:
## ! non-equidistant arg-values in 'MIMS_tf' ignored by rollmean.</code></pre>
<p>The resulting <code>MIMS_hour</code> data are shown for a subset of
participants in the Figure below. As before, we are interested in the
effects of <code>age</code>, now treated as a continuous variable, and
<code>gender</code>.</p>
<pre class="r"><code>nhanes_df %>%
ggplot(aes(y = MIMS_hour, color = age)) +
geom_spaghetti(alpha = .2) +
geom_meatballs(alpha = .2) +
facet_grid(.~gender) +
scale_x_continuous(
breaks = seq(0, 24, length = 5),
labels = str_c(seq(0, 24, length = 5), ":00")) +
labs(x = "Time of day (hours)", y = "MIMS")</code></pre>
<p><img src="chapter_05_files/figure-html/unnamed-chunk-4-1.png" width="90%" /></p>
<p>These data can be analyzed using hour-specific linear models that
regress bin-average MIMS values on <code>age</code> and
<code>gender</code>. This does not account for the temporal structure of
the diurnal profiles except through the binning that aggregates data.We
fit a standard linear model for with the average MIMS value between 1:00
and 2:00pm as a response by we unnesting the hour-level functional
observations and subset to the interval of current interest.</p>
<pre class="r"><code>linear_fit =
nhanes_df %>%
select(SEQN, age, gender, MIMS_hour) %>%
tf_unnest(MIMS_hour) %>%
filter(MIMS_hour_arg == 13.5) %>%
lm(MIMS_hour_value ~ age + gender, data = .)</code></pre>
<p>Here is a table showing regression results.</p>
<table>
<thead>
<tr class="header">
<th align="left">term</th>
<th align="right">estimate</th>
<th align="right">std.error</th>
<th align="right">statistic</th>
<th align="right">p.value</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">(Intercept)</td>
<td align="right">16.836</td>
<td align="right">0.883</td>
<td align="right">19.059</td>
<td align="right">0.000</td>
</tr>
<tr class="even">
<td align="left">age</td>
<td align="right">-0.079</td>
<td align="right">0.016</td>
<td align="right">-4.939</td>
<td align="right">0.000</td>
</tr>
<tr class="odd">
<td align="left">genderFemale</td>
<td align="right">1.041</td>
<td align="right">0.608</td>
<td align="right">1.714</td>
<td align="right">0.088</td>
</tr>
</tbody>
</table>
<p>And here is a scatterplot illustrating the regression at this time
point.</p>
<pre class="r"><code>nhanes_df %>%
select(SEQN, age, gender, MIMS_hour) %>%
tf_unnest(MIMS_hour) %>%
filter(MIMS_hour_arg == 13.5) %>%
modelr::add_predictions(linear_fit) %>%
ggplot(aes(x = age, y = MIMS_hour_value, color = gender)) +
geom_point(alpha = .5, lwd = .9) +
geom_line(aes(y = pred), linewidth = 1.1) +
labs(x = "Age", y = "Hour Average MIMS")
## Warning in geom_point(alpha = 0.5, lwd = 0.9): Ignoring unknown parameters:
## `linewidth`</code></pre>
<p><img src="chapter_05_files/figure-html/unnamed-chunk-7-1.png" width="90%" /></p>
<p>In this plot, the binned-average MIMS values decrease with age, and
female participants may have somewhat higher values than male
participants.</p>
<p>Associations between binned-average MIMS values and <code>age</code>
and <code>gender</code> will vary by hour. Next we unnest the
subject-specific functional observation and then re-nest within hour;
the result is a dataframe containing 24 rows, one for each hour, with a
column that contains a list of hour-specific dataframes containing the
<code>MIMS_hour_value</code>, <code>age</code>, and <code>gender</code>.
By mapping over the entries in this list, we can fit hour-specific
linear models and extract tidied results.</p>
<pre class="r"><code>hourly_regressions =
nhanes_df %>%
select(SEQN, age, gender, MIMS_hour) %>%
tf_unnest(MIMS_hour) %>%
rename(hour = MIMS_hour_arg, MIMS = MIMS_hour_value) %>%
nest(data = -hour) %>%
mutate(
model = map(.x = data, ~lm(MIMS ~ age + gender, data = .x)),
result = map(model, broom::tidy)
) %>%
select(hour, result)</code></pre>
<p>We process these results obtain hourly confidence intervals and then
structure coefficient estimates and confidence bands as <code>tf</code>
objects. The result is a three-row dataframe, with rows for the
intercept, age, and gender effects; columns include the term name as
well as the coefficient estimates and the upper and lower limits of the
confidence bands.</p>
<pre class="r"><code>hour_bin_coefs =
hourly_regressions %>%
unnest(cols = result) %>%
rename(coef = estimate, se = std.error) %>%
mutate(
ub = coef + 1.96 * se,
lb = coef - 1.96 * se
) %>%
select(hour, term, coef, ub, lb) %>%
tf_nest(coef:lb, .id = term, .arg = hour)</code></pre>
<p>Because the coefficient estimates in <code>coef</code> are
<code>tf</code> objects, we can plot these using
<code>geom_spaghetti</code> in <a
href="https://tidyfun.github.io/tidyfun/"><code>tidyfun</code></a>; to
emphasize the estimates at each hour, we add points using
<code>geom_meatballs</code>. Confidence bands are shown by specifying
the upper and lower limits, and we facet by term to see each coefficient
separately.</p>
<pre class="r"><code>hour_bin_coefs %>%
ggplot(aes(y = coef, color = term)) +
geom_spaghetti() +
geom_meatballs() +
geom_errorband(aes(ymax = ub, ymin = lb, fill = term)) +
facet_wrap("term", scales = "free") +
scale_x_continuous(
breaks = seq(0, 24, length = 5),
labels = str_c(seq(0, 24, length = 5), ":00")) +
labs(x = "Time of day (hours)", y = "Coefficient")</code></pre>
<p><img src="chapter_05_files/figure-html/unnamed-chunk-10-1.png" width="90%" /></p>
<p>The intercept shows a fairly typical diurnal pattern, with low
activity in the night and higher activity in the day. After adjusting
for age, women are somewhat less active in the middle of the night but
more active during the daytime hours. Meanwhile, after adjusting for
gender, older participants are generally less active at all times.</p>
<p>The hour-level analysis is an informative exploratory approach, but
has several limitations. Most obviously, it aggregates data within
prespecified bins, and in doing so loses some of the richness of the
underlying data. That aggregation induces some smoothness by relying on
the underlying temporal structure, but this smoothness is implicit and
dependent on the bins that are chosen. To emphasize these points, we can
repeat the bin-level analysis using 1-minute epochs.</p>
<pre class="r"><code>min_regressions =
nhanes_df %>%
select(SEQN, age, gender, MIMS_tf) %>%
tf_unnest(MIMS_tf) %>%
rename(epoch = MIMS_tf_arg, MIMS = MIMS_tf_value) %>%
nest(data = -epoch) %>%
mutate(
model = map(.x = data, ~lm(MIMS ~ age + gender, data = .x)),
result = map(model, broom::tidy)
) %>%
select(epoch, result) %>%
unnest(result)
min_regressions =
min_regressions %>%
rename(coef = estimate, se = std.error) %>%
mutate(
ub = coef + 1.96 * se,
lb = coef - 1.96 * se
) %>%
select(epoch, term, coef, ub, lb) %>%
tf_nest(coef:lb, .id = term, .arg = epoch) %>%
mutate(method = "Pointwise") %>%
relocate(method)</code></pre>
<p>Results for one-minute epochs are in the next figure.</p>
<pre class="r"><code>min_regressions %>%
ggplot(aes(y = coef, color = term)) +
geom_spaghetti() +
geom_meatballs() +
geom_errorband(aes(ymax = ub, ymin = lb, fill = term)) +
facet_wrap("term", scales = "free") +
scale_x_continuous(
breaks = seq(0, 24, length = 5),
labels = str_c(seq(0, 24, length = 5), ":00")) +
labs(x = "Time of day (hours)", y = "Coefficient")</code></pre>
<p><img src="chapter_05_files/figure-html/unnamed-chunk-13-1.png" width="90%" /></p>
<p>The qualitative results and their interpretations are similar – the
intercept suggests a usual circadian rhythm, and the age indicates that
activity generally decreases with increasing age, and the gender effect
shows that female participants were more active than male participants.
But this also shows some difficulties inherent in binning-based
analyses. These do not leverage the temporal structure directly in the
estimation process. A correct approach to inference is not obvious, both
because of the need for some degree of smoothness across time and also
because within-subject residuals will have a temporal correlation
structure. A more subtle issue is that we implicitly rely on curves
being observed over the same grid, or at least that a rolling mean is a
plausible way to generate binned averages, and this approach may not
work when data are sparse or irregular across subjects.</p>
<p>Solutions to these problems are the goal of various approaches to
function-on-scalar regression, which seeks to explicitly model
coefficients in a way that induces smoothness; in some way accounts for
within-curve correlation; and extends to a variety of data generating
scenarios.</p>
</div>
</div>
<div id="linear-function-on-scalar-regression" class="section level2">
<h2>Linear Function-on-Scalar Regression</h2>
<p>Let <span class="math inline">\(y_i:\mathcal{S}\rightarrow
\mathbb{R}\)</span> be a functional response of interest for each study
participant, <span class="math inline">\(i=1,\ldots,n\)</span>, and
<span class="math inline">\(x_{i1}\)</span> and <span
class="math inline">\(x_{i2}\)</span> be two scalar predictors. In the
example on this page, the functional response is the MIMS profile for
each participant, and the scalar predictors of interest are age in years
and a variable indicating whether participant <span
class="math inline">\(i\)</span> is male (<span
class="math inline">\(x_{i2} = 0\)</span>) or female (<span
class="math inline">\(x_{i2} = 1\)</span>). The linear
function-on-scalar regression for this setting is <span
class="math display">\[E[Y_i(s)] = \beta_0(s) + \beta_1(s) x_{i1} +
\beta_2(s) x_{i2}\]</span> with coefficients <span
class="math inline">\(\beta_q:\mathcal{S}\rightarrow
\mathbb{R}\)</span>, <span class="math inline">\(q \in \{0, 1,
2\}\)</span> that are functions measured over the same domain as the
response. Scalar covariates in this model can exhibit the same degree of
complexity as in non-functional regressions, allowing any number of
continuous and categorical predictors of interest.</p>
<p>Coefficient functions encode the varying association between the
response and predictors, and are interpretable in ways that parallel
non-functional regression models. In particular, <span
class="math inline">\(\beta_0(s)\)</span> is the expected response for
<span class="math inline">\(x_{i1} = x_{i2} = 0\)</span>; <span
class="math inline">\(\beta_1(s)\)</span> is the expected change in the
response for each one unit change in <span
class="math inline">\(x_{i1}\)</span> while holding <span
class="math inline">\(x_{i2}\)</span> constant; and so on. These are
often interpreted at specific values of <span class="math inline">\(s
\in \mathcal{S}\)</span> to gain intuition for the associations of
interest. Residuals in this model will contain deviations between the
observed responses and the expected values based on the linear
predictor.</p>
<p>The linear FoSR model has several advantages. Because coefficients
are functions observed on <span
class="math inline">\(\mathcal{S}\)</span>, they can be estimated using
techniques that explicitly allow for smoothness across the functional
domain. This smoothness, along with appropriate error correlation
structures, provides an avenue for correct statistical inference.
Considering coefficients as functions also opens the door to data
generating mechanisms for observed data that would be challenging or
impossible in more exploratory settings, such as responses that are
observed on grids that are sparse or irregular across subjects.</p>
<div id="estimation-of-fixed-effects" class="section level3">
<h3>Estimation of Fixed Effects</h3>
<p>Functional responses are observed over a discrete grid <span
class="math inline">\(\mathbf{s} = \{s_1, ..., s_J\}\)</span> which, for
now, we will assume to be common across subjects so that for subject
<span class="math inline">\(i\)</span> the observed data vector is <span
class="math inline">\(\mathbf{y}_i^{T} = [y_i(s_1), ...,
y_i(s_J)]\)</span>. From the FoSR, we have <span
class="math display">\[E[\mathbf{y}_i^{T}] =
\mathbf{x}_i \begin{bmatrix}
\beta_{0}(s_1) & ... & \beta_{0}(s_J)\\
\beta_{1}(s_1) & ... & \beta_{2}(s_J)\\
\beta_{2}(s_1) & ... & \beta_{3}(s_J)
\end{bmatrix} \]</span> where <span class="math inline">\(\mathbf{x}_i =
[1, x_{i1}, x_{i2}]\)</span> is the row vector containing scalar terms
that defines the regression model. This expression is useful because it
connects a <span class="math inline">\(1 \times J\)</span> response
vector to a recognizable row in a standard regression design matrix and
the matrix of functional coefficients.</p>
<p>Estimation of coefficients will rely on approaches that have been
used elsewhere with nuances specific to the FoSR setting. As a starting
point, we will expand each <span class="math inline">\(\beta_q(s) =
\sum_{k=1}^K\beta_{qk} B_k(s)\)</span> using the basis <span
class="math inline">\(B_1(s),\ldots,B_K(s)\)</span>. While many choices
are possible, we will use a spline expansion. Using this, the <span
class="math inline">\(3 \times J\)</span> matrix of coefficient
functions can be expressed using <span class="math display">\[
\begin{bmatrix}
\beta_{11} & \beta_{21} & \beta_{31}\\
\vdots & \vdots & \vdots \\
\beta_{1K} & \beta_{2K} & \beta_{3K}
\end{bmatrix}
\begin{bmatrix}
\boldsymbol{B}_{1}(s_1) & ... & \boldsymbol{B}_{K}(s_1)\\
\vdots & & \vdots \\
\boldsymbol{B}_{1}(s_J) & ... & \boldsymbol{B}_{K}(s_J)
\end{bmatrix}.
\]</span></p>
<p>Conveniently, one can concisely combine and rewrite the previous
expressions. Let <span class="math inline">\(\boldsymbol{B}(s_{j}) =
[B_1(s_{j}), \ldots, B_K(s_{j})]\)</span> be the <span
class="math inline">\(1 \times K\)</span> row vector containing the
basis functions evaluated at <span class="math inline">\(s_{j}\)</span>
and <span class="math inline">\(\boldsymbol{B}(\mathbf{s})\)</span> be
the <span class="math inline">\(K \times J\)</span> matrix containing
basis functions evaluated over the grid <span
class="math inline">\(\mathbf{s}\)</span>. Further, let <span
class="math inline">\(\mathbf{\beta}_{q} = [\beta_{q1}, \ldots,
\beta_{qK}]^{T}\)</span> be the <span class="math inline">\(K \times
1\)</span> vector of basis coefficients for function <span
class="math inline">\(p\)</span> and <span
class="math inline">\(\boldsymbol{\beta} = [\mathbf{\beta}^{T}_{0},
\mathbf{\beta}^{T}_{1}, \mathbf{\beta}^{T}_{2}]^{T}\)</span> be the
<span class="math inline">\((3 \cdot K) \times 1\)</span> vector
constructed by stacking the vectors of basis coefficients. For the <span
class="math inline">\(J \times 1\)</span> response vector <span
class="math inline">\(\mathbf{y}_i\)</span>, we have <span
class="math display">\[
E[\mathbf{y}_i] = [\mathbf{x}_i \otimes \boldsymbol{B}(\mathbf{s})]
\boldsymbol{\beta}
\]</span> where <span class="math inline">\(\otimes\)</span> is the
Kronecker product.</p>
<p>This expression for a single subject can be directly extended to all
subjects. Let <span class="math inline">\(\mathbf{y}\)</span> be the
<span class="math inline">\((n \cdot J) \times 1\)</span> vector created
by stacking the vectors <span
class="math inline">\(\mathbf{y}_i\)</span> and <span
class="math inline">\(\boldsymbol{X}\)</span> be <span
class="math inline">\(n \times 3\)</span> matrix created by stacking the
vectors <span class="math inline">\(\mathbf{x}_i\)</span>. Then <span
class="math display">\[
E[\mathbf{y}] = [\boldsymbol{X} \otimes \boldsymbol{B}(\mathbf{s})]
\boldsymbol{\beta}.
\]</span> This formulation, while somewhat confusing at first, underlies
many implementations of the linear FoSR model. First, we note that the
matrix <span class="math inline">\(\boldsymbol{X}\)</span> is the design
matrix familiar from non-functional regression models, and includes a
row for each subject and a column for each predictor. The Kronecker
product with the basis <span
class="math inline">\(\boldsymbol{B}(\mathbf{s})\)</span> replicates
that basis once for each coefficient function; this product also ensures
that each coefficient function, evaluated over <span
class="math inline">\(\mathbf{s}\)</span>, is multiplied by the
subject-specific covariate vector <span
class="math inline">\(\mathbf{x}_i\)</span>. Finally, considering <span
class="math inline">\([\boldsymbol{B}(\mathbf{s}) \otimes
\boldsymbol{X}]\)</span> as the full FoSR design matrix and <span
class="math inline">\(\boldsymbol{\beta}\)</span> as a vector of
coefficients to be estimated explicitly connects the FoSR model to
standard regression techniques.</p>
<div id="estimation-using-ordinary-least-squares"
class="section level4">
<h4>Estimation using ordinary least squares</h4>
<p>Estimation the spline coefficients helps to build intuition for the
inner workings of more complex estimation strategies. We will regress
the daily MIMS data on age and gender to illustrate this approach.
Recall that <code>nhanes_df</code> stores <code>MIMS</code> as a
<code>tf</code> vector; some of the code below relies on extracting
information from a <code>tf</code> object.</p>
<p>For this model, the code chunk below defines the standard design
matrix <span class="math inline">\(\boldsymbol{X}\)</span> and the
response vector <span class="math inline">\(\mathbf{y}\)</span>. The
call to <code>model.matrix()</code> uses a formula that correctly
specifies the predictors, and obtaining the response vector
<code>y</code> unnests the <code>tf</code> vector and then extracts the
observed responses for each subject.</p>
<pre class="r"><code>X_des =
model.matrix(
SEQN ~ gender + age,
data = nhanes_df
)
y =
nhanes_df %>%
tf_unnest(MIMS_tf) %>%
pull(MIMS_tf_value)</code></pre>
<p>The next code chunk constructs the spline basis matrix <span
class="math inline">\(\boldsymbol{B}(\mathbf{s})\)</span> and the
Kronecker product <span
class="math inline">\([\boldsymbol{B}(\mathbf{s}) \otimes
\boldsymbol{X}]\)</span>. The spline basis is evaluated over the grid
<span class="math inline">\(\mathbf{s}\)</span> pulled from
<code>MIMS</code>, and uses <span class="math inline">\(K = 30\)</span>
basis functions.</p>
<pre class="r"><code>epoch_arg = seq(1/60, 24, length = 1440)
basis =
splines::bs(epoch_arg, df = 30, intercept = TRUE)
X_kron_B = kronecker(X_des, basis)</code></pre>
<p>Using these, the direct application of usual formulas provides OLS
estimates of the spline coefficients. Reconstructing coefficient
functions is possible, and the results can be converted to a
<code>tf</code> vector for plotting and manipulation. The code chunk
below estimates spline coefficients.</p>
<pre class="r"><code>spline_coefs = solve(t(X_kron_B) %*% X_kron_B) %*% t(X_kron_B) %*% y</code></pre>
<p>We now construct, organize, and plot coefficient functions.</p>
<pre class="r"><code>OLS_coef_df =
tibble(
method = "OLS",
term = colnames(X_des),
coef =
tfd(
t(basis %*% matrix(spline_coefs, nrow = 30)),
arg = epoch_arg)
)
OLS_coef_df %>%
ggplot(aes(y = coef, color = term)) +
geom_spaghetti(lwd = 1.1, alpha = .75) +
facet_wrap("term", scales = "free") +
scale_x_continuous(
breaks = seq(0, 24, length = 5),
labels = str_c(seq(0, 24, length = 5), ":00")) +
labs(x = "Time of day (hours)", y = "Coefficient")</code></pre>
<p><img src="chapter_05_files/figure-html/unnamed-chunk-17-1.png" width="90%" /></p>
<p>Comparing these results to those obtained from epoch-specific
regressions begins to indicate the benefits of a functional perspective.
We will next incorporate smoothness penalties and account for complex
error correlations, but it is helpful to view these as variations on a
familiar regression framework.</p>
</div>
<div id="estimation-using-smoothness-penalties" class="section level4">
<h4>Estimation using smoothness penalties</h4>
<p>Spline expansions for coefficient functions in the linear FoSR model
makes the functional nature of the observed data and the model
parameters explicit, and distinguishes this approach from multivariate
or epoch-based alternatives. However, using a spline expansion
introduces questions about how best to balance flexibility with
goodness-of-fit. It is common to use a large value for <span
class="math inline">\(K\)</span> and introduce smoothness-enforcing
penalties to prevent overfitting.</p>
<p>Solutions obtained using OLS also arise using maximum likelihood
estimation. Assume that residuals <span
class="math inline">\(\mathbf{\epsilon}_i^{T} = [\epsilon_i(s_1), ...,
\epsilon_i(s_J)]\)</span> observed on <span
class="math inline">\(\mathbf{s}\)</span> are <span
class="math inline">\(\mathrm{iid}\)</span> are drawn from a mean-zero
normal distribution with variance <span
class="math inline">\(\sigma^{2}_{\epsilon}\)</span> that is constant
over time points <span class="math inline">\(\mathbf{s}\)</span> and
subjects <span class="math inline">\(i\)</span>. Maximizing the (log)
likelihood <span class="math inline">\(\mathcal{L}(\boldsymbol{\beta};
\mathbf{y})\)</span> induced by this assumption with respect to spline
coefficients is equivalent to the OLS approach. We can add penalties
<span class="math inline">\(P\left[\beta_{q}(s) \right]\)</span> to
enforce smoothness in estimates of coefficient functions; a common
choice is the second derivative penalty <span
class="math inline">\(\int_{\mathcal{S}} \left[\beta_{q}^{''}(s)
\right]^2 ds\)</span>. The second derivative penalty and many others can
be expressed in terms of the corresponding coefficient vector, resulting
in the penalized likelihood <span class="math display">\[
\mathcal{L}(\boldsymbol{\beta}; \mathbf{y}) + \sum_{q} \lambda_{q}
P\left[\mathbf{\beta}_{q} \right]\]</span> where tuning parameters <span
class="math inline">\(\lambda_{q}\)</span> control the balance between
goodness-of-fit and complexity of the coefficient functions <span
class="math inline">\(\beta_{q}(s)\)</span>.</p>
<p>Here we are emphasizing a penalized likelihood approach rather than
using the penalized residual sum of squares. Focusing on the penalized
likelihood makes the extension to non-continuous response functions
(e.g. binary rest-active trajectories instead of MIMS profiles)
relatively direct by changing the assumed outcome distribution, and will
similarly facilitate modeling and including error correlation
structures. More importantly, it is possible to view the
likelihood-based framework as a variation on mixed-model approaches to
penalized spline smooth smoothing emphasized throughout the book, and
which underlies many FoSR implementations.</p>
<p>We will use the <code>gam</code> function in the well-developed
<code>mgcv</code> package to fit the FoSR model with smoothness
penalties. First, we explicitly create the binary indicator variable for
<code>gender</code>, and organize data into “long” format by unnesting
the MIMS data stored as a <code>tf</code> object. The resulting
dataframe has a row for each subject and epoch, containing the
<code>MIMS</code> outcome in that epoch as well as the scalar covariates
of interest. This is analogous to the creation of the response vector
for model fitting using OLS, and begins to organize covariates for
inclusion in a design matrix.</p>
<pre class="r"><code>nhanes_for_gam =
nhanes_df %>%
mutate(gender = as.numeric(gender == "Female")) %>%
tf_unnest(MIMS_tf) %>%
rename(epoch = MIMS_tf_arg, MIMS = MIMS_tf_value)</code></pre>
<p>With data in this form, we can fit the FoSR model using
<code>mgcv::gam()</code> as follows.</p>
<pre class="r"><code>gam_fit =
gam(MIMS ~ s(epoch) + s(epoch, by = gender) + s(epoch, by = age),
data = nhanes_for_gam)</code></pre>
<p>Conceptually, this specification indicates that each observed
<code>MIMS</code> value is the combination of three smooth functions of
<code>epoch</code>: an intercept function, and the products of
coefficient functions and scalar covariates <code>gender</code> and
<code>age</code>. Specifically, the first model term
<code>s(epoch)</code> indicates the evaluation of a spline expansion
over values contained in the <code>epoch</code> column of the data frame
<code>nhanes_for_gam</code>. The second and third terms add
<code>by = gender</code> and <code>by = age</code>, respectively, which
also indicate spline expansions over the <code>epoch</code> column but
multiply the result by the corresponding scalar covariates. This process
is analogous to the creation of the design matrix <span
class="math inline">\([\boldsymbol{B}(\mathbf{s}) \otimes
\boldsymbol{X}]\)</span>, although <code>gam()</code>’s function
<code>s()</code> allows users to flexibly specify additional options for
each basis expansion.</p>
<p>In contrast to parameter estimation using OLS, smoothness is induced
in parameter estimates through explicit penalization. By default,