-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path06-modeling.Rmd
1595 lines (1098 loc) · 50.6 KB
/
06-modeling.Rmd
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
---
title: "Introduction to Data Science"
subtitle: "Session 6: Model fitting <s>and simulation</s>"
author: "Simon Munzert"
institute: "Hertie School | [GRAD-C11/E1339](https://github.com/intro-to-data-science-21)" #"`r format(Sys.time(), '%d %B %Y')`"
output:
xaringan::moon_reader:
css: [default, 'simons-touch.css', metropolis, metropolis-fonts]
lib_dir: libs
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
ratio: '16:9'
hash: true
---
```{css, echo=FALSE}
@media print { # print out incremental slides; see https://stackoverflow.com/questions/56373198/get-xaringan-incremental-animations-to-print-to-pdf/56374619#56374619
.has-continuation {
display: block !important;
}
}
```
```{r setup, include=FALSE}
# figures formatting setup
options(htmltools.dir.version = FALSE)
library(knitr)
opts_chunk$set(
comment = " ",
prompt = T,
fig.align="center", #fig.width=6, fig.height=4.5,
# out.width="748px", #out.length="520.75px",
dpi=300, #fig.path='Figs/',
cache=F, #echo=F, warning=F, message=F
engine.opts = list(bash = "-l")
)
## Next hook based on this SO answer: https://stackoverflow.com/a/39025054
knit_hooks$set(
prompt = function(before, options, envir) {
options(
prompt = if (options$engine %in% c('sh','bash')) '$ ' else 'R> ',
continue = if (options$engine %in% c('sh','bash')) '$ ' else '+ '
)
})
library(tidyverse)
library(nycflights13)
library(modelsummary)
library(kableExtra)
```
# Table of contents
<br>
1. [Crafting formulas](#formulas)
2. [Running models](#models)
3. [Processing estimation output](#postestimation)
4. [Reporting modeling results](#reporting)
5. [Simulating fake data](#simulation)
6. [Summary](#summary)
---
# Workshop information
### More rules
- We have a preliminary schedule online. Check the [Google Spreadsheet](https://docs.google.com/spreadsheets/d/12djhhUG8USmEUm-wPby5VAjsEj_S4ZO8kWsayUOlHPg/edit?usp=sharing) (link on Moodle) and save the date/time slot. Use the comment feature if the slot does not work for you.
- Please upload your presentation video on Moodle (new assignment at the bottom; see description for more details). Deadline is November 1, 11.59pm CET (NO extension possible).
- The labs on Oct 27 will provide you with more details about screen recording, preparation of materials etc.
- Please note that the deadline for assignment 4 (model fitting) has been extended to Nov 10.
--
### How the workshop will be run
- The videos will be hosted on Hertie's Vimeo account and embedded on a dedicated workshop webpage.
- The workshop will run on MS Teams in a dedicated Team. You'll be invited soon.
- We will have three parallel sessions.
- Session presenters will also moderate their session.
- The session starts with video, then comes the live tutorial.
- You can attend as many other sessions as you want, but I expect you to attend AT LEAST two other sessions.
---
# Workshop information (cont.)
### Goals for the presentation
- The topics vary in breadth and potential depth. I don't expect you to go very deep.
- You should not assume any prior knowledge among your fellow students (other than the topics and tools that have been covered in class).
- Try to offer a quick yet engaging overview: What is this tool/technique/package good for? How can we use it? What are the key features? Where should students go to learn more?
--
### Goals for the live tutorial
- The tutorial should be structured around the practice material that you provide for the session.
- You don't have to cover everything in the material though. It could make sense to focus on one aspect and let students engage with it / work on it.
- All students will have access to (and hopefully have downloaded) all materials in advance. You can encourage them to follow along on their machines if that makes sense. Be sure to include code that installs the necessary packages though.
---
# Workshop information (cont.)
### How to split topics between groups and team members
- Groups that have been assigned the same topic prepare separate sessions You can exchange ideas but the sessions should work as standalone units.
- It is up to you to split the work in your team. For the live session it would be ideal if both of you attend. It is absolutely mandatory that at least one of you attends and moderates the session.
--
### Grading
- Both the recorded talk and the prepared exercise materials will be graded.
- For the prepared exercise materials we will pull the repositories that you created on the workshop GitHub page. You'll be provided with a README.md template that you will use to summarize the content of your session and to document who contributed to which parts of the unit.
---
background-image: url("pics/data-model-jesus.jpeg")
background-size: contain
background-color: #000000
# The modeling workflow
`Credit` [David Hood](https://twitter.com/Thoughtfulnz/status/1446972794135216131)
---
# The modeling workflow
.pull-left-wide[
### Why modeling?
- Modeling is at the heart of the data science workflow.
- We use models to explore, test, infer, predict based on data.
- The art and science of statistical modeling is vast.
- Today, we will focus on key steps of the workflow which are common in most modeling endeavors. We won't touch on theoretical/statistical backgrounds though and ignore workflow issues in particular areas, such as simulation-based Bayesian inference.
]
--
.pull-right-small[
### Steps of the workflow
1. **Choose** a modeling strategy
2. **Specify** the model (structural components / parameters)
3. **Run/implement** the model (estimation)
4. **Evaluate** the model output
5. **Present** the results
]
--
<div align="center">
<br>
<img src="pics/data-science-model.png" width=550>
</div>
<!-- ############################################ -->
---
class: inverse, center, middle
name: formulas
# Crafting formulas
<html><div style='float:left'></div><hr color='#EB811B' size=1px style="width:1000px; margin:auto;"/></html>
---
background-image: url("pics/albert-einstein-lm.png")
background-size: contain
background-color: #000000
# Crafting formulas
---
# Model building
### Systematic + stochastic components of models
- When we try to model data, we often start by assuming a data-generating process that looks like
$$Y = f(x) + \epsilon$$
- In doing so, we decompose a model (or data-generating process) into a random or stochastic part (here: $\epsilon$) and a systematic/structural/deterministic part (here: $f(x)$).
- (We might go on to impose further assumptions about the stochastic component, e.g., $\epsilon \sim N(0, \sigma^2)$.)
- In many cases, we want to learn how certain variables systematically relate to each other. To that end, we specify the systematic component of a model and then "let the data speak" to estimate parameters associate with elements of the systematic component.
- As an example, we might specify
$$f(x) = \beta_{0} + \beta_{1}x$$
- But how can we express our belief about the model structure in R?
---
# Model building in R
### Model formulas in R
- In R, there's a standardized way to specify models like this: working with the `formula` class.
- In many cases you can still think of the model formula as just a string specifying the structural part of your model (there are exceptions).
- But `formula` class objects also allow you to do more useful things with formula.
- The basic structure of a formula is the tilde symbol (~) and at least one independent (righthand) variable. In most (but not all) situations, a single dependent (lefthand) variable is also needed. Thus we can construct a formula quite simply by just typing:
```{r, eval = FALSE}
y ~ x
```
- Spaces in formulas are not important, but I recommend using them to make the formulas more readable.
- Running a model with a formula is straightforward. Note that we don't even have to put the formula in parentheses - it is automatically interpreted as one formula expression when provided as the first argument:
```{r, eval = FALSE}
lm(arr_delay ~ distance + origin, data = flights)
```
---
# Model formulas in R (cont.)
### Storing formulas
- A more explicit way is to write the formula as string and then use `as.formula()` to turn it into a formula object. This implies that we can store formulas as an R object and check its class.
```{r, eval = TRUE}
fmla <- as.formula("arr_delay ~ distance + origin")
class(fmla)
```
- Next, we'd pass on the `formula` object to the model function, e.g.:
```{r, eval = TRUE}
lm(fmla, data = flights)
```
---
# Formula syntax: basics
- We can use multiple independent variables by simply separating them with the plus (+) symbol:
```{r, eval = FALSE}
y ~ x1 + x2
```
- If we use a minus (-) symbol, objects in the formula are ignored in an analysis:
```{r, eval = FALSE}
y ~ x1 - x2
```
- We can also use this to drop the intercept:
```{r, eval = FALSE}
y ~ x1 - x2 - 1
```
- The `.` operator refers to all other variables in the matrix/data frame not yet included in the model. This is useful when you plan to run a regression on all variables in a matrix/data frame:
```{r, eval = FALSE}
y ~ .
```
---
# Formula syntax: interactions
In a regression modeling context, we often need to specify interaction terms. There are two ways to do this. If we want to include two variables and their interaction, we use the star/asterisk (`*`) symbol:
```{r, eval = FALSE}
y ~ x1 * x2
```
That's equivalent to
```{r, eval = FALSE}
y ~ x1 + x2 + x1*x2
```
If you only want their interaction, but not the variables themselves as main effects (which you probably don't want), use the colon symbol:
```{r, eval = FALSE}
y ~ x1:x2
```
---
# Formula syntax: variable transformations
One trick to formulas is that they don't evaluate their contents. So, for example, if we wanted to include $x$ and $x^2$ in our model, we might be tempted to type:
```{r, eval = FALSE}
y ~ x + x^2
```
This won't work though. We therefore have to either calculate and store all of the variables we want to include in the model in advance, or we need to use the `I()` "as-is" operator, short for "Inhibit Interpretation/Conversion of Objects". In a formula function, `I()` is used to inhibit the interpretation of operators such as `+`, `-`, `*` and `^` as formula operators, so they are used as arithmetical operators. To obtain our desired two-term formula, we type:
```{r, eval = FALSE}
y ~ x + I(x^2)
```
Again, the alternative would have been something like:
```{r, eval = FALSE}
data$x2 <- (data$x)^2
y ~ x + x2
```
---
# Specifying multiple models
### When one model is not enough
- Often we want to specify not one but multiple different models.
- Such models can differ in terms of model family, modelled outcome, covariate/feature set, transformations of input variables, and data being modelled.
### Generating model formulas at scale
- If outcomes/features vary across models, so does the model formula.
- Regarding formulas as character strings, it's straightforward to generate them in a programmatic fashion.
--
**Example:**
```{r, eval = TRUE}
xvars <- paste0("x", 1:20)
fmla <- as.formula(paste("y ~ ", paste(xvars, collapse= "+")))
fmla
```
---
# Specifying multiple models (cont.)
- Another example of multiple model specification is [extreme bounds analysis (EBA)](https://en.wikipedia.org/wiki/Extreme_bounds_analysis).
- Here, the idea is to compute all possible estimates given a set of allowed coefficients to answer questions like:
- Which determinants are robustly associated with the dependent variable across a large number of possible regression models?
- Is a particular determinant robustly associated with the dependent variable?
- In its basic form, EBA just estimates models with all possible combinations of variables and then looks into the distribution (or range → extreme bounds) of effects across all models.
- There are R packages to do this for us (e.g., `ExtremeBounds` [by Marek Hlavac](https://cran.r-project.org/web/packages/ExtremeBounds/vignettes/ExtremeBounds.pdf)) but we can also run the basics on our own.
--
### Example
**Step 1: Define dependent variable and covariate set**
```{r, eval = TRUE}
depvar <- "arr_delay"
covars <- c("dep_delay", "carrier", "origin", "air_time", "distance", "hour")
```
---
# Specifying multiple models (cont.)
**Step 1a (just for fun): Compute the number of unique combinations of all these covariates**
```{r, eval = TRUE}
combinations <-
map(1:6, function(x) {combn(1:6, x)}) %>% # create all possible combinations (draw 1 to 6 out of 6)
map(ncol) %>% # extract number of combinations
unlist() %>% # pull out of list structure
sum() # compute sum
```
---
# Specifying multiple models (cont.)
**Step 2: Build function to run lm models across set of all possible variable combinations **
```{r, eval = TRUE}
combn_models <- function(depvar, covars, data)
{
combn_list <- list()
# generate list of covariate combinations
for (i in seq_along(covars)) {
combn_list[[i]] <- combn(covars, i, simplify = FALSE)
}
combn_list <- unlist(combn_list, recursive = FALSE)
# function to generate formulas
gen_formula <- function(covars, depvar) {
form <- as.formula(paste0(depvar, " ~ ", paste0(covars, collapse = "+")))
form
}
# generate formulas
formulas_list <- purrr::map(combn_list, gen_formula, depvar = depvar)
# run models
models_list <- purrr::map(formulas_list, lm, data = data)
models_list
}
```
---
# Specifying multiple models (cont.)
**Step 3: Run models (careful, this'll generate a quite heavy list)**
```{r, eval = TRUE, echo = FALSE, include = FALSE}
models_list <- combn_models(depvar = depvar, covars = covars, data = sample_n(flights, 10000))
length(models_list)
models_list[[1]]
```
```{r, eval = FALSE}
models_list <- combn_models(depvar = depvar, covars = covars, data = flights)
```
How many models did we fit?
```{r, eval = TRUE}
length(models_list)
```
And what did we get? A glimpse at the first list element:
```{r, eval = TRUE}
models_list[[1]]
```
<!-- ############################################ -->
---
class: inverse, center, middle
name: models
# Running models
<html><div style='float:left'></div><hr color='#EB811B' size=1px style="width:1000px; margin:auto;"/></html>
---
background-image: url("pics/turing-bombe.jpeg")
background-size: contain
background-color: #000000
# Running models
---
# Model families
Today we'll mostly focus on linear models as an example. However, there is a multitude of families of statistical models that allow extend linear models. Examples are
- **Generalized linear models** [`stats::glm()`], which extend linear models to include non-continuous responses (e.g., binary or categorical data, counts)
- **Generalized additive models** [`mgcv::gam()`], which extend generalized linear models to incorporate arbitrary smooth functions
- **Penalized linear models** [`glmnet::glmnet()`], which introduce terms that penalize complex models to make models that generalize better to new datasets
--
Also there is so much more to learn in terms of [modeling/machine learning/AI](https://en.wikipedia.org/wiki/Machine_learning). There are many (MANY!) models for measurement, (un-)supervised learning, clustering, dimensionality reduction, ... R is uniquely flexible for implementing these models. To get a quick glance at the universe from afar, check out the [CRAN Task Views](https://cran.r-project.org/web/views/), a curated online directory of topics and the R packages relevant for tasks related to these.
---
# Running models: examples
Luckily, these models work all similarly from a programming experience - once you've mastered how to run linear models, you will find it easy to implement others. Understanding and applying them wisely is a different matter though.
**Logistic regression**
```{r, eval = FALSE}
logit_out <- stats::glm(am ~ cyl + hp + wt, data = mtcars, family = binomial)
```
**Generalized additive model regression**
```{r, eval = FALSE}
gam_out <- mgcv::gam(mpg ~ s(disp) + s(wt), data = mtcars)
```
**Penalized (here: lasso) regression**
```{r, eval = FALSE}
lasso_out <- glmnet(as.matrix(mtcars[-1]), mtcars[,1], standardize = TRUE, alpha = 1)
```
**Multilevel model with random intercepts**
```{r, eval = FALSE}
library(lme4)
ml_out <- lmer(arr_delay ~ distance + origin + (1|carrier) + (1|tailnum), data = flights)
```
---
# Decisions in the modeling workflow
.pull-left[
### Big data and the need for models
- In the early days of the big data hype, people were overly enthusiastic about its implications for modeling (see quote on the right).
- This is falling for the inception that we can simply "let the data speak".
- However, the data science workflow is a sequence of subjective decisions from start to finish, with lots of researcher degrees of freedom.
- Think of all the weakly justified decisions regarding:
- data collection / selection
- measurement
- model choice
- model specification
- reporting
]
.pull-right[
<br><br>
<div style="background-color:rgba(0, 0, 0, 0.1)">
"Scientists are trained to recognize that correlation is not causation, that no conclusions should be drawn simply on the basis of correlation between X and Y. (...) Once you have a model, you can connect the data sets with confidence. Data without a model is just noise. (...) There is now a better way. Petabytes allow us to say: "Correlation is enough." We can stop looking for models. We can analyze the data without hypotheses about what it might show."
</div>
*Chris Anderson*, ["The End of Theory: The Data Deluge makes the Scientific Method Obsolete (2008, *Wired*)"](https://www.wired.com/2008/06/pb-theory/)
]
---
# Decisions in the modeling workflow
.pull-left[
### Big data and the need for models
- In the early days of the big data hype, people were overly enthusiastic about its implications for modeling (see quote on the right).
- This is falling for the inception that we can simply "let the data speak".
- However, the data science workflow is a sequence of subjective decisions from start to finish, with lots of researcher degrees of freedom.
- Think of all the weakly justified decisions regarding:
- data collection / selection
- measurement
- model choice
- model specification
- reporting
**Question:** How do researchers usually deal with this?
]
.pull-right[
<br><br>
<div style="background-color:rgba(0, 0, 0, 0.1)">
"Scientists are trained to recognize that correlation is not causation, that no conclusions should be drawn simply on the basis of correlation between X and Y. (...) Once you have a model, you can connect the data sets with confidence. Data without a model is just noise. (...) There is now a better way. Petabytes allow us to say: "Correlation is enough." We can stop looking for models. We can analyze the data without hypotheses about what it might show."
</div>
*Chris Anderson*, ["The End of Theory: The Data Deluge makes the Scientific Method Obsolete (2008, *Wired*)"](https://www.wired.com/2008/06/pb-theory/)
]
---
# Nested models
.pull-left-center[
<div align="center">
<img src="pics/nested-models-chen.png" width=600>
</div>
`Credit` Chen 2010, [The Effect of Electoral Geography on Pork Barreling in Bicameral Legislatures](https://www.jstor.org/stable/25652208)
]
.pull-right-center[
<div align="center">
<br><br>
<img src="pics/nested-models-park.png" width=600>
</div>
`Credit` Park et al. 2009, [Being immersed in social networking environment: Facebook groups, uses and gratifications, and social outcomes](https://pubmed.ncbi.nlm.nih.gov/19619037/)
]
---
# Exploring the model space
.pull-left[
- **Another idea:** run not an arbitrary (small) set of models but as many (plausible ones) as possible to get an idea how much conclusions change depending on arbitrary data wrangling and modeling choices (the "model distribution").
- There are various related procedures and labels used in different subfields to promote this idea, including:
- Multiverse analysis ([Steegen et al. 2016](https://journals.sagepub.com/doi/10.1177/1745691616658637))
- Specification curves ([Simonsohn et al. 2020](https://www.nature.com/articles/s41562-020-0912-z))
- Computational multimodel analysis ([Young and Holsteen 2015](http://fmwww.bc.edu/repec/bocode/m/Model_Uncertainty_and_Robustness.pdf))
- Also check out critical perspective on "[Mülltiverse Analysis](http://www.the100.ci/2021/03/07/mulltiverse-analysis/)" (Julia Rohrer). The bottom line: Mindless multiversing doesn't give more robustness or insight.
]
.pull-right[
<div align="center">
<img src="pics/multiverse-analysis-1.png" width=450>
<img src="pics/multimodel-analysis.png" width=230>
</div>
]
---
# Specification curves
.pull-left[
- Specification curve analysis (SCA) facilitates the visual identification of the source of variation in results across multiple specifications.
- The key feature, the specification curve, provides all gathered estimates sorted by effect size and highlighted by significance.
- SCA is carried out in three main steps:
1. Define the set of reasonable specifications to estimate;
2. Estimate all specifications and report the results in a descriptive specification curve; and
3. Conduct joint statistical tests using an inferential specification curve.
- As of now there are two R packages that offer high-level functions for specification: `specr` (see [here](https://cran.r-project.org/web/packages/specr/vignettes/specr.html)) and `Multiverse` (see [here](https://mucollective.github.io/multiverse/)).
]
.pull-right[
<div align="center">
<br>
<img src="pics/specification-curve-1.png" width=550>
<br>
<br>
<img src="pics/specification-curve-2.png" width=550>
</div>
]
---
# Specification curves (cont.)
<div align="center">
<img src="pics/specification-curve-3.png" width=850>
</div>
<!-- ############################################ -->
---
class: inverse, center, middle
name: postestimation
# Processing estimation output
<html><div style='float:left'></div><hr color='#EB811B' size=1px style="width:1000px; margin:auto;"/></html>
---
background-image: url("pics/computer-nerd-mod.jpg")
background-size: contain
background-color: #000000
# Processing estimation output
---
# Why model processing?
.pull-left-small2[
When estimating a model, we usually estimate parameters (or simulate distributions thereof). There is, however, more that we can take away from the estimation, including:
]
.pull-right-wide2[
```{r, eval = FALSE, prompt = FALSE}
summary(model_out)
Call:
lm(formula = arr_delay ~ distance + origin, data = flights)
Residuals:
Min 1Q Median 3Q Max
-89.04 -24.00 -11.83 7.26 1281.45
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 13.4140488 0.1748144 76.73 <2e-16 ***
distance -0.0040451 0.0001097 -36.87 <2e-16 ***
originJFK -2.7042552 0.1887083 -14.33 <2e-16 ***
originLGA -4.4561694 0.1935123 -23.03 <2e-16 ***
---
Sig. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 44.51 on 327342 degrees of freedom
(9430 observations deleted due to missingness)
Multiple R-squared: 0.005503, Adjusted R-squared: 0.005493
F-statistic: 603.7 on 3 and 327342 DF, p-value: < 2.2e-16
```
]
---
# Why model processing?
.pull-left-small2[
When estimating a model, we usually estimate parameters (or simulate distributions thereof). There is, however, more that we can take away from the estimation, including:
- **Estimated coefficients** and associated standard errors, T-statistics, p-values, confidence intervals
]
.pull-right-wide2[
```{r, eval = FALSE, prompt = FALSE}
summary(model_out)
Call:
lm(formula = arr_delay ~ distance + origin, data = flights)
Residuals:
Min 1Q Median 3Q Max
-89.04 -24.00 -11.83 7.26 1281.45
Coefficients: #<<
Estimate Std. Error t value Pr(>|t|) #<<
(Intercept) 13.4140488 0.1748144 76.73 <2e-16 *** #<<
distance -0.0040451 0.0001097 -36.87 <2e-16 *** #<<
originJFK -2.7042552 0.1887083 -14.33 <2e-16 *** #<<
originLGA -4.4561694 0.1935123 -23.03 <2e-16 *** #<<
--- #<<
Sig. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 #<<
Residual standard error: 44.51 on 327342 degrees of freedom
(9430 observations deleted due to missingness)
Multiple R-squared: 0.005503, Adjusted R-squared: 0.005493
F-statistic: 603.7 on 3 and 327342 DF, p-value: < 2.2e-16
```
]
---
# Why model processing?
.pull-left-small2[
When estimating a model, we usually estimate parameters (or simulate distributions thereof). There is, however, more that we can take away from the estimation, including:
- **Estimated coefficients** and associated standard errors, T-statistics, p-values, confidence intervals
- **Model summaries**, including goods of fit measures, information on model convergence, number of observations used
]
.pull-right-wide2[
```{r, eval = FALSE, prompt = FALSE}
summary(model_out)
Call:
lm(formula = arr_delay ~ distance + origin, data = flights)
Residuals:
Min 1Q Median 3Q Max
-89.04 -24.00 -11.83 7.26 1281.45
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 13.4140488 0.1748144 76.73 <2e-16 ***
distance -0.0040451 0.0001097 -36.87 <2e-16 ***
originJFK -2.7042552 0.1887083 -14.33 <2e-16 ***
originLGA -4.4561694 0.1935123 -23.03 <2e-16 ***
---
Sig. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 44.51 on 327342 degrees of freedom #<<
(9430 observations deleted due to missingness) #<<
Multiple R-squared: 0.005503, Adjusted R-squared: 0.005493 #<<
F-statistic: 603.7 on 3 and 327342 DF, p-value: < 2.2e-16 #<<
```
]
---
# Why model processing?
.pull-left-small2[
When estimating a model, we usually estimate parameters (or simulate distributions thereof). There is, however, more that we can take away from the estimation, including:
- **Estimated coefficients** and associated standard errors, T-statistics, p-values, confidence intervals
- **Model summaries**, including goods of fit measures, information on model convergence, number of observations used
- **Observation-level information** that arises from the estimated model, such as fitted/predicted values, residuals, estimates of influence
]
.pull-right-wide2[
```{r, eval = FALSE, prompt = FALSE}
summary(model_out)
Call:
lm(formula = arr_delay ~ distance + origin, data = flights)
Residuals: #<<
Min 1Q Median 3Q Max #<<
-89.04 -24.00 -11.83 7.26 1281.45 #<<
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 13.4140488 0.1748144 76.73 <2e-16 ***
distance -0.0040451 0.0001097 -36.87 <2e-16 ***
originJFK -2.7042552 0.1887083 -14.33 <2e-16 ***
originLGA -4.4561694 0.1935123 -23.03 <2e-16 ***
---
Sig. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 44.51 on 327342 degrees of freedom
(9430 observations deleted due to missingness)
Multiple R-squared: 0.005503, Adjusted R-squared: 0.005493
F-statistic: 603.7 on 3 and 327342 DF, p-value: < 2.2e-16
```
]
---
# Processing estimation output in R
.pull-left-small[
- Fitting a model returns an object of a certain model class (here: `lm`).
- Printing that object returns a quite minimalist set of information - just the input formula and coefficients.
]
.pull-right-wide[
```{r, eval = TRUE}
model_out <- lm(arr_delay ~ distance + origin, data = flights)
class(model_out)
model_out
```
]
---
# Processing estimation output in R
.pull-left-small[
- Fitting a model returns an object of a certain model class (here: `lm`).
- Printing that object returns a quite minimalist set of information - just the input formula and coefficients.
- The anatomy of the object is considerably more complex. It comes as a list of various components, including the coefficients, residuals, fitted values, and original model input.
]
.pull-right-wide[
```{r, eval = TRUE}
names(model_out)
```
]
---
# Processing estimation output in R
.pull-left-small[
- Fitting a model returns an object of a certain model class (here: `lm`).
- Printing that object returns a quite minimalist set of information - just the input formula and coefficients.
- The anatomy of the object is considerably more complex. It comes as a list of various components, including the coefficients, residuals, fitted values, and original model input.
- There's no way to print this list the slide in full - it's just too long.
]
.pull-right-wide[
```{r, eval = TRUE}
str(model_out)
```
]
---
# Processing estimation output in R
.pull-left-small[
- However, there are some high-level functions we can apply to do something useful with the model object, including:
- `coef()` to extract the coefficients
]
.pull-right-wide[
```{r, eval = TRUE}
coef(model_out)
```
]
---
# Processing estimation output in R
.pull-left-small[
- However, there are some high-level functions we can apply to do something useful with the model object, including:
- `coef()` to extract the coefficients
- `fitted.values()` to extract the outcome values predicted by the model
]
.pull-right-wide[
```{r, eval = TRUE}
coef(model_out)
fitted.values(model_out)[1:5]
```
]
---
# Processing estimation output in R
.pull-left-small[
- However, there are some high-level functions we can apply to do something useful with the model object, including:
- `coef()` to extract the coefficients
- `fitted.values()` to extract the outcome values predicted by the model
- `residuals()` to extract the residuals
]
.pull-right-wide[
```{r, eval = TRUE}
coef(model_out)
fitted.values(model_out)[1:5]
residuals(model_out)[1:5]
```
]
---
# Processing estimation output in R
.pull-left-small[
- However, there are some high-level functions we can apply to do something useful with the model object, including:
- `coef()` to extract the coefficients
- `fitted.values()` to extract the outcome values predicted by the model
- `residuals()` to extract the residuals
- `model.matrix()` to extract the matrix of original input variables (predictors)
]
.pull-right-wide[
```{r, eval = TRUE}
coef(model_out)
fitted.values(model_out)[1:5]
residuals(model_out)[1:5]
model.matrix(model_out) %>% head(4)
```
]
---
# Processing estimation output in R
.pull-left-small[
- To learn more about the estimated model, we can apply the `summary()` function.
- The `summary` method is specific to the model class it is applied to (here: "`lm` "). To learn more, you'd have to call, e.g., `?summary.lm` or `?summary.glm`.
]
.pull-right-wide[
```{r, eval = TRUE}
summary(model_out)
```
]
---
# Processing estimation output in R
.pull-left-small[
- To learn more about the estimated model, we can apply the `summary()` function.
- The `summary` method is specific to the model class it is applied to (here: "`lm` "). To learn more, you'd have to call, e.g., `?summary.lm` or `?summary.glm`.
- The function creates more than a printed summary in the console. It returns an object of class `summary.lm`, which can be further dissected.
]
.pull-right-wide[
```{r, eval = TRUE}
class(summary(model_out))
```
]
---
# Processing estimation output in R
.pull-left-small[
- To learn more about the estimated model, we can apply the `summary()` function.
- The `summary` method is specific to the model class it is applied to (here: "`lm` "). To learn more, you'd have to call, e.g., `?summary.lm` or `?summary.glm`.
- The function creates more than a printed summary in the console. It returns an object of class `summary.lm`, which can be further dissected.
- Again, there's no way to print this list on the slide in full - it's just too long.