-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathregression.Rmd
1694 lines (1254 loc) · 48.5 KB
/
regression.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: "Regression"
output:
html_document:
code_folding: show
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
echo = TRUE,
error = TRUE,
comment = "",
class.source = "fold-show")
```
# Preamble
## Install Libraries
```{r, class.source = "fold-hide"}
#install.packages("remotes")
#remotes::install_github("DevPsyLab/petersenlab")
```
## Load Libraries
```{r, message = FALSE, warning = FALSE, class.source = "fold-hide"}
library("petersenlab")
library("MASS")
library("tidyverse")
library("psych")
library("rms")
library("robustbase")
library("brms")
library("cvTools")
library("car")
library("mgcv")
library("AER")
library("foreign")
library("olsrr")
library("quantreg")
library("mblm")
library("effects")
library("correlation")
library("interactions")
library("lavaan")
library("regtools")
library("mice")
library("XICOR")
library("cocor")
```
# Import Data
```{r, eval = FALSE, class.source = "fold-hide"}
mydata <- read.csv("https://osf.io/8syp5/download")
```
```{r, include = FALSE}
mydata <- read.csv("./data/cnlsy.csv") #https://osf.io/8syp5/download
```
# Data Preparation
```{r, class.source = "fold-hide"}
mydata$countVariable <- as.integer(mydata$bpi_antisocialT2Sum)
mydata$orderedVariable <- factor(mydata$countVariable, ordered = TRUE)
mydata$female <- NA
mydata$female[which(mydata$sex == "male")] <- 0
mydata$female[which(mydata$sex == "female")] <- 1
```
# Linear Regression
## Linear regression model
```{r}
multipleRegressionModel <- lm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = na.exclude)
summary(multipleRegressionModel)
confint(multipleRegressionModel)
```
### Remove missing data
```{r}
multipleRegressionModelNoMissing <- lm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = na.omit)
multipleRegressionModelNoMissing <- lm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata %>% select(bpi_antisocialT2Sum, bpi_antisocialT1Sum, bpi_anxiousDepressedSum) %>% na.omit)
```
## Linear regression model on correlation/covariance matrix (for pairwise deletion)
```{r, warning = FALSE}
multipleRegressionModelPairwise <- setCor(
y = "bpi_antisocialT2Sum",
x = c("bpi_antisocialT1Sum","bpi_anxiousDepressedSum"),
data = cov(mydata[,c("bpi_antisocialT2Sum","bpi_antisocialT1Sum","bpi_anxiousDepressedSum")], use = "pairwise.complete.obs"),
n.obs = nrow(mydata))
summary(multipleRegressionModelPairwise)
multipleRegressionModelPairwise[c("coefficients","se","Probability","R2","shrunkenR2")]
```
## Linear regression model with robust covariance matrix (rms)
```{r}
rmsMultipleRegressionModel <- robcov(ols(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
x = TRUE,
y = TRUE))
rmsMultipleRegressionModel
confint(rmsMultipleRegressionModel)
```
## Robust linear regression (MM-type iteratively reweighted least squares regression)
```{r}
robustLinearRegression <- lmrob(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = na.exclude)
summary(robustLinearRegression)
confint(robustLinearRegression)
```
## Least trimmed squares regression (for removing outliers)
```{r}
ltsRegression <- ltsReg(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = na.exclude)
summary(ltsRegression)
```
## Bayesian linear regression
```{r, message = FALSE, warning = FALSE, results = FALSE}
bayesianRegularizedRegression <- brm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
chains = 4,
iter = 2000,
seed = 52242)
```
```{r}
summary(bayesianRegularizedRegression)
```
# Generalized Linear Regression
## Generalized regression model
In this example, we predict a count variable that has a poisson distribution.
We could change the distribution.
```{r}
generalizedRegressionModel <- glm(
countVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
family = "poisson",
na.action = na.exclude)
summary(generalizedRegressionModel)
confint(generalizedRegressionModel)
```
## Generalized regression model (rms)
In this example, we predict a count variable that has a poisson distribution.
We could change the distribution.
```{r}
rmsGeneralizedRegressionModel <- Glm(
countVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
x = TRUE,
y = TRUE,
family = "poisson")
rmsGeneralizedRegressionModel
confint(rmsGeneralizedRegressionModel)
```
## Bayesian generalized linear model
In this example, we predict a count variable that has a poisson distribution.
We could change the distribution.
For example, we could use Gamma regression, `family = Gamma`, when the response variable is continuous and positive, and the coefficient of variation--rather than the variance--is constant.
```{r, message = FALSE, warning = FALSE, results = FALSE}
bayesianGeneralizedLinearRegression <- brm(
countVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
family = poisson,
chains = 4,
seed = 52242,
iter = 2000)
```
```{r}
summary(bayesianGeneralizedLinearRegression)
```
## Robust generalized regression
```{r}
robustGeneralizedRegression <- glmrob(
countVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
family = "poisson",
na.action = na.exclude)
summary(robustGeneralizedRegression)
confint(robustGeneralizedRegression)
```
## Ordinal regression model
```{r}
ordinalRegressionModel1 <- polr(
orderedVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata)
ordinalRegressionModel2 <- lrm(
orderedVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
x = TRUE,
y = TRUE)
ordinalRegressionModel3 <- orm(
orderedVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
x = TRUE,
y = TRUE)
summary(ordinalRegressionModel1)
confint(ordinalRegressionModel1)
ordinalRegressionModel2
ordinalRegressionModel3
confint(ordinalRegressionModel3)
```
## Bayesian ordinal regression model
```{r, message = FALSE, warning = FALSE, results = FALSE}
bayesianOrdinalRegression <- brm(
orderedVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
family = cumulative(),
chains = 4,
seed = 52242,
iter = 2000)
```
```{r}
summary(bayesianOrdinalRegression)
```
## Bayesian count regression model
```{r, message = FALSE, warning = FALSE, results = FALSE}
bayesianCountRegression <- brm(
countVariable ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
family = "poisson",
chains = 4,
seed = 52242,
iter = 2000)
```
```{r}
summary(bayesianCountRegression)
```
## Logistic regression model (rms)
```{r}
logisticRegressionModel <- robcov(lrm(
female ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
x = TRUE,
y = TRUE))
logisticRegressionModel
confint(logisticRegressionModel)
```
## Bayesian logistic regression model
```{r, message = FALSE, warning = FALSE, results = FALSE}
bayesianLogisticRegression <- brm(
female ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
family = bernoulli,
chains = 4,
seed = 52242,
iter = 2000)
```
```{r}
summary(bayesianLogisticRegression)
```
# Hierarchical Linear Regression
```{r}
model1 <- lm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum,
data = mydata %>% select(bpi_antisocialT2Sum, bpi_antisocialT1Sum, bpi_anxiousDepressedSum) %>% na.omit,
na.action = na.exclude)
model2 <- lm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata %>% select(bpi_antisocialT2Sum, bpi_antisocialT1Sum, bpi_anxiousDepressedSum) %>% na.omit,
na.action = na.exclude)
summary(model2)$adj.r.squared
anova(model1, model2)
summary(model2)$adj.r.squared - summary(model1)$adj.r.squared
```
# Moderated Multiple Regression {#moderation}
https://cran.r-project.org/web/packages/interactions/vignettes/interactions.html (archived at https://perma.cc/P34H-7BH3)
```{r}
states <- as.data.frame(state.x77)
```
## Mean Center Predictors
Make sure to mean-center or orthogonalize predictors before computing the interaction term.
```{r}
states$Illiteracy_centered <- scale(states$Illiteracy, scale = FALSE)
states$Murder_centered <- scale(states$Murder, scale = FALSE)
```
## Model
```{r}
interactionModel <- lm(
Income ~ Illiteracy_centered + Murder_centered + Illiteracy_centered:Murder_centered + `HS Grad`,
data = states)
```
## Plots
```{r}
interact_plot(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered)
interact_plot(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered,
plot.points = TRUE)
interact_plot(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered,
interval = TRUE)
johnson_neyman(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered,
alpha = .05)
```
## Simple Slopes Analysis
```{r}
sim_slopes(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered,
johnson_neyman = FALSE)
sim_slopes(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered,
modx.values = c(0, 5, 10),
johnson_neyman = FALSE)
```
## Johnson-Neyman intervals
Indicates all the values of the moderator for which the slope of the predictor is statistically significant.
```{r}
sim_slopes(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered,
johnson_neyman = TRUE)
probe_interaction(
interactionModel,
pred = Illiteracy_centered,
modx = Murder_centered,
cond.int = TRUE,
interval = TRUE,
jnplot = TRUE)
```
# Comparing Correlations {#compareCorrelations}
Fisher's *r*-to-*z* test.
http://comparingcorrelations.org (archived at https://perma.cc/X3EU-24GL)
Independent groups (two different groups):
```{r}
cocor::cocor.indep.groups(
r1.jk = .7,
r2.hm = .6,
n1 = 305,
n2 = 210,
data.name = c("group1", "group2"),
var.labels = c("age", "intelligence", "age", "intelligence"))
```
Dependent groups (same group), overlapping correlation (shares a variable in common—in this case, the variable `age` is shared in both correlations):
```{r}
cocor::cocor.dep.groups.overlap(
r.jk = .2, # Correlation (age, intelligence)
r.jh = .5, # Correlation (age, shoe size)
r.kh = .1, # Correlation (intelligence, shoe index)
n = 315,
var.labels = c("age", "intelligence", "shoe size"))
```
Dependent groups (same group), non-overlapping correlation (does not share a variable in common):
```{r}
cocor::cocor.dep.groups.nonoverlap(
r.jk = .2, # Correlation (age, intelligence)
r.hm = .7, # Correlation (body mass index, shoe size)
r.jh = .4, # Correlation (age, body mass index)
r.jm = .5, # Correlation (age, shoe size)
r.kh = .1, # Correlation (intelligence, body mass index)
r.km = .3, # Correlation (intelligence, shoe size)
n = 232,
var.labels = c("age", "intelligence", "body mass index", "shoe size"))
```
# Approaches to Handling Missingness {#missingness}
## Listwise deletion {#listwiseDeletion}
Listwise deletion deletes every row in the data file that has a missing value for one of the model variables.
```{r}
listwiseDeletionModel <- lm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = na.exclude)
summary(listwiseDeletionModel)
confint(listwiseDeletionModel)
```
## Pairwise deletion {#pairwiseDeletion}
Also see here:
- https://stats.stackexchange.com/questions/158366/fit-multiple-regression-model-with-pairwise-deletion-or-on-a-correlation-covari/173002#173002 (archived at https://perma.cc/GH5T-RXD9)
- https://stats.stackexchange.com/questions/299792/r-lm-covariance-matrix-manual-calculation-failure (archived at https://perma.cc/F7EL-AUFZ)
- https://stats.stackexchange.com/questions/107597/is-there-a-way-to-use-the-covariance-matrix-to-find-coefficients-for-multiple-re (archived at https://perma.cc/KU3X-FB2C)
- https://stats.stackexchange.com/questions/105006/how-to-perform-a-bivariate-regression-using-pairwise-deletion-of-missing-values (archived at https://perma.cc/QWQ5-2TLW)
- https://dl.dropboxusercontent.com/s/4sf0et3p47ykctx/MissingPairwise.sps (archived at https://perma.cc/UC4K-2L9T)
Adapted from here: https://stefvanbuuren.name/fimd/sec-simplesolutions.html#sec:pairwise (archived at https://perma.cc/EGU6-3M3Q)
```{r}
modelData <- mydata[,c("bpi_antisocialT2Sum","bpi_antisocialT1Sum","bpi_anxiousDepressedSum")]
varMeans <- colMeans(modelData, na.rm = TRUE)
varCovariances <- cov(modelData, use = "pairwise")
pairwiseRegression_syntax <- '
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum
bpi_antisocialT2Sum ~~ bpi_antisocialT2Sum
bpi_antisocialT2Sum ~ 1
'
pairwiseRegression_fit <- lavaan(
pairwiseRegression_syntax,
sample.mean = varMeans,
sample.cov = varCovariances,
sample.nobs = sum(complete.cases(modelData))
)
summary(
pairwiseRegression_fit,
standardized = TRUE,
rsquare = TRUE)
```
## Full-information maximum likelihood (FIML) {#fiml}
```{r}
fimlRegression_syntax <- '
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum
bpi_antisocialT2Sum ~~ bpi_antisocialT2Sum
bpi_antisocialT2Sum ~ 1
'
fimlRegression_fit <- lavaan(
fimlRegression_syntax,
data = mydata,
missing = "ML",
)
summary(
fimlRegression_fit,
standardized = TRUE,
rsquare = TRUE)
```
## Multiple imputation {#imputation}
```{r}
modelData_imputed <- mice(
modelData,
m = 5,
method = "pmm") # predictive mean matching; can choose among many methods
imputedData_fit <- with(
modelData_imputed,
lm(bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum))
imputedData_pooledEstimates <- pool(imputedData_fit)
summary(imputedData_pooledEstimates)
```
# Model Building Steps
1. Examine extent and type of missing data, consider [how to handle missing values](#missingness) ([multiple imputation](#imputation), [FIML](#fiml), [pairwise deletion](#pairwiseDeletion), [listwise deletion](#listwiseDeletion))
- Little's MCAR test from `mcar_test()` function of the `njtierney/naniar` package
- Bayesian handling of missing data: https://cran.r-project.org/web/packages/brms/vignettes/brms_missings.html (archived at https://perma.cc/Z4HT-QXWR)
1. Examine descriptive statistics, consider variable transformations
1. Examine scatterplot matrix to examine whether associations between predictor and outcomes are linear or nonlinear
1. Model building: theory and empiricism (stepwise regression, likelihood ratio tests, k-fold cross validation to check for over-fitting compared to simpler model)
1. Test assumptions
- Examine whether predictors have linear association with outcome (Residual Plots, Marginal Model Plots, Added-Variable Plots—check for non-horizontal lines)
- Examine whether residuals have constant variance across levels of outcome and predictors Residual Plots, Spread-Level Plots—check for fan-shaped plot or other increasing/decreasing structure)
- Examine whether predictors show multicollinearity (VIF)
- Examine whether residuals are normally distributed (QQ plot and density plot)
- Examine influence of influential observations (high outlyingness and leverage) on parameter stimates by iteratively removing influential observations and refitting (Added-Variable Plots)
1. Handle violated assumptions, select final set of predictors/outcomes and transformation of each
1. Use k-fold cross validation to identify the best estimation procedure (OLS, MM, or LTS) on the final model
1. Use identified estimation procedure to fit final model and determine the best parameter point estimates
1. Calculate bootstrapped estimates to determine the confidence intervals around the parameter estimates of the final model
# Bootstrapped Estimates
To determine the confidence intervals of parameter estimates
## Linear Regression
```{r}
multipleRegressionModelBootstrapped <- Boot(multipleRegressionModelNoMissing, R = 1000)
summary(multipleRegressionModelBootstrapped)
confint(multipleRegressionModelBootstrapped, level = .95, type = "bca")
hist(multipleRegressionModelBootstrapped)
```
## Generalized Regression
```{r}
generalizedRegressionModelBootstrapped <- Boot(multipleRegressionModelNoMissing, R = 1000)
summary(generalizedRegressionModelBootstrapped)
confint(generalizedRegressionModelBootstrapped, level = .95, type = "bca")
hist(generalizedRegressionModelBootstrapped)
```
# Cross Validation
To examine degree of prediction error and over-fitting to determine best model
https://stats.stackexchange.com/questions/103459/how-do-i-know-which-method-of-cross-validation-is-best (archived at https://perma.cc/38BL-KLRJ)
## K-fold cross validation
```{r}
kFolds <- 10
replications <- 20
folds <- cvFolds(nrow(mydata), K = kFolds, R = replications)
fitLm <- lm(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = "na.exclude")
fitLmrob <- lmrob(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = "na.exclude")
fitLts <- ltsReg(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
na.action = "na.exclude")
cvFitLm <- cvLm(
fitLm,
K = kFolds,
R = replications)
cvFitLmrob <- cvLmrob(
fitLmrob,
K = kFolds,
R = replications)
cvFitLts <- cvLts(
fitLts,
K = kFolds,
R = replications)
cvFits <- cvSelect(
OLS = cvFitLm,
MM = cvFitLmrob,
LTS = cvFitLts)
cvFits
bwplot(
cvFits,
xlab = "Root Mean Square Error",
xlim = c(0, max(cvFits$cv$CV) + 0.2))
```
# Examining Model Fits
## Effect Plots
```{r}
allEffects(multipleRegressionModel)
plot(allEffects(multipleRegressionModel))
```
## Confidence Ellipses
```{r}
confidenceEllipse(
multipleRegressionModel,
levels = c(0.5, .95))
```
## Data Ellipse
```{r}
mydata_nomissing <- na.omit(mydata[,c("bpi_antisocialT1Sum","bpi_antisocialT2Sum")])
dataEllipse(
mydata_nomissing$bpi_antisocialT1Sum,
mydata_nomissing$bpi_antisocialT2Sum,
levels = c(0.5, .95))
```
# Diagnostics
## Assumptions
### 1. Linear relation between predictors and outcome {#linearAssociation}
#### Ways to Test
##### Before Model Fitting
- scatterplot matrix
- distance correlation
###### Scatterplot Matrix
```{r}
scatterplotMatrix(
~ bpi_antisocialT2Sum + bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata)
```
###### Distance correlation
The distance correlation is an index of the degree of the linear and non-linear association between two variables.
```{r}
correlation(
mydata[,c("bpi_antisocialT1Sum","bpi_antisocialT2Sum")],
method = "distance",
p_adjust = "none")
```
##### After Model Fitting
Check for nonlinearities (non-horizontal line) in plots of:
- Residuals versus fitted values ([Residual Plots](#residualPlots))—best
- Residuals versus predictors ([Residual Plots](#residualPlots))
- Outcome versus fitted values ([Marginal Model Plots](#marginalModelPlots))
- Outcome versus predictors, ignoring other predictors ([Marginal Model Plots](#marginalModelPlots))
- Outcome versus predictors, controlling for other predictors ([Added-Variable Plots](#addedVariablePlots))
#### Ways to Handle
- Transform outcome/predictor variables (Box-Cox transformations)
- Semi-parametric regression models: Generalized additive models (GAM)
- Non-parametric regression models: Nearest-Neighbor Kernel Regression
##### Semi-parametric or non-parametric regression models
http://www.lisa.stat.vt.edu/?q=node/7517 (archived at https://web.archive.org/web/20180113065042/http://www.lisa.stat.vt.edu/?q=node/7517)
Note: using semi-parametric or non-parametric models increases fit in context of nonlinearity at the expense of added complexity.
Make sure to avoid fitting an overly complex model (e.g., use k-fold cross validation).
Often, the simpler (generalized) linear model is preferable to semi-paremetric or non-parametric approaches
###### Semi-parametric: Generalized Additive Models
http://documents.software.dell.com/Statistics/Textbook/Generalized-Additive-Models (archived at https://web.archive.org/web/20170213041653/http://documents.software.dell.com/Statistics/Textbook/Generalized-Additive-Models)
```{r}
generalizedAdditiveModel <- gam(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
family = gaussian(),
data = mydata,
na.action = na.exclude)
summary(generalizedAdditiveModel)
confint(generalizedAdditiveModel)
```
###### Non-parametric: Nearest-Neighbor Kernel Regression
### 2. Exogeneity
Exogeneity means that the association between predictors and outcome is fully causal and unrelated to other variables.
#### Ways to Test
- Durbin-Wu-Hausman test of endogeneity
##### Durbin-Wu-Hausman test of endogeneity
The instrumental variables (2SLS) estimator is implemented in the `R` package `AER` as command:
```{r, eval = FALSE}
ivreg(y ~ x1 + x2 + w1 + w2 | z1 + z2 + z3 + w1 + w2)
```
where `x1` and `x2` are endogenous regressors, `w1` and `w2` exogeneous regressors, and `z1` to `z3` are excluded instruments.
Durbin-Wu-Hausman test:
```{r, eval = FALSE}
hsng2 <- read.dta("https://www.stata-press.com/data/r11/hsng2.dta") #archived at https://perma.cc/7P2Q-ARKR
```
```{r, include = FALSE}
hsng2 <- read.dta("./data/hsng2.dta") #https://www.stata-press.com/data/r11/hsng2.dta archived at https://perma.cc/7P2Q-ARKR
```
```{r}
fiv <- ivreg(
rent ~ hsngval + pcturban | pcturban + faminc + reg2 + reg3 + reg4,
data = hsng2) #Housing values are likely endogeneous and therefore instrumented by median family income (faminc) and 3 regional dummies (reg2, reg4, reg4)
summary(
fiv,
diagnostics = TRUE)
```
The Eicker-Huber-White covariance estimator which is robust to heteroscedastic error terms is reported after estimation with `vcov = sandwich` in `coeftest()`
First stage results are reported by explicitly estimating them.
For example:
```{r}
first <- lm(
hsngval ~ pcturban + faminc + reg2 + reg3 + reg4,
data = hsng2)
summary(first)
```
In case of a single endogenous variable (K = 1), the F-statistic to assess weak instruments is reported after estimating the first stage with, for example:
```{r}
waldtest(
first,
. ~ . - faminc - reg2 - reg3 - reg4)
```
or in case of heteroscedatistic errors:
```{r}
waldtest(
first,
. ~ . - faminc - reg2 - reg3- reg4,
vcov = sandwich)
```
#### Ways to Handle
- Conduct an experiment/RCT with random assignment
- Instrumental variables
### 3. Homoscedasticity of residuals
Homoscedasticity of the residuals means that the variance of the residuals does not differ as a function of the outcome/predictors (i.e., the residuals show constant variance as a function of outcome/predictors).
#### Ways to Test
- Plot residuals vs. outcome and predictor variables ([Residual Plots](#residualPlots))
- Plot residuals vs. fitted values ([Residual Plots](#residualPlots))
- Time Series data: Plot residuals vs. time
- Spread-level plot
- Breusch-Pagan test: `bptest()` function from `lmtest` package
- Goldfeld-Quandt Test
##### Residuals vs. outcome and predictor variables
Plot residuals, or perhaps their absolute values, versus the outcome and predictor variables ([Residual Plots](#residualPlots)).
Examine whether residual variance is constant at all levels of other variables or whether it increases/decreases as a function of another variable (or shows some others structure, e.g., small variance at low and high levels of a predictor and high variance in the middle).
Note that this is *different than whether the residuals show non-linearities*—i.e., a non-horizontal line, which would indicate a [nonlinear association between variables](#linearAssociation) (see Assumption #1, above).
Rather, here we are examining whether there is change in the variance as a function of another variable (e.g., a fan-shaped [Residual Plot](#residualPlots))
##### Spread-level plot
Examining whether level (e.g., mean) depends on spread (e.g., variance)—plot of log of the absolute Studentized residuals against the log of the fitted values
```{r}
spreadLevelPlot(multipleRegressionModel)
```
##### Breusch-Pagan test
https://www.rdocumentation.org/packages/lmtest/versions/0.9-40/topics/bptest (archived at https://perma.cc/K4WC-7TVW)
```{r}
bptest(multipleRegressionModel)
```
##### Goldfeld-Quandt Test
```{r}
gqtest(multipleRegressionModel)
```
##### Test of dependence of spread on level
```{r}
ncvTest(multipleRegressionModel)
```
##### Test of dependence of spread on predictors
```{r}
ncvTest(
multipleRegressionModel,
~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum)
```
#### Ways to Handle
- If residual variance increases as a function of the fitted values, consider a poisson regression model (especially for count data), for which the variance does increase with the mean
- If residual variance differs as a function of model predictors, consider adding interactions/product terms (the effect of one variable depends on the level of another variable)
- Try transforming the outcome variable to be normally distributed (log-transform if the errors seem consistent in percentage rather than absolute terms)
- If the error variance is proportional to a variable $z$, then fit the model using Weighted Least Squares (WLS), with the weights given be $1/z$
- Weighted least squares (WLS) using the "weights" argument of the `lm()` function; to get weights, see: https://stats.stackexchange.com/a/100410/20338 (archived at https://perma.cc/C6BY-G9MS)
- Huber-White standard errors (a.k.a. "Sandwich" estimates) from a heteroscedasticity-corrected covariance matrix
- `coeftest()` function from the `sandwich` package along with hccm sandwich estimates from the `car` package
- `robcov()` function from the `rms` package
- Time series data: ARCH (auto-regressive conditional heteroscedasticity) models
- Time series data: seasonal patterns can be addressed by applying log transformation to outcome variable
##### Huber-White standard errors
Standard errors (SEs) on the diagonal increase
```{r}
vcov(multipleRegressionModel)
hccm(multipleRegressionModel)
summary(multipleRegressionModel)
coeftest(multipleRegressionModel, vcov = sandwich)
coeftest(multipleRegressionModel, vcov = hccm)
robcov(ols(
bpi_antisocialT2Sum ~ bpi_antisocialT1Sum + bpi_anxiousDepressedSum,
data = mydata,
x = TRUE,
y = TRUE))
robcov(ols(
t_ext ~ m_ext + age,
data = mydata,
x = TRUE,
y = TRUE),
cluster = mydata$tcid) #account for nested data within subject
```
### 4. Errors are independent
Independent errors means that the errors are uncorrelated with each other.
#### Ways to Test
- Plot residuals vs. predictors ([Residual Plots](#residualPlots))
- Time Series data: Residual time series plot (residuals vs. row number)
- Time Series data: Table or plot of residual autocorrelations
- Time Series data: Durbin-Watson statistic for test of significant residual autocorrelation at lag 1
#### Ways to Handle
- Generalized least squares (GLS) models are capable of handling correlated errors: https://stat.ethz.ch/R-manual/R-devel/library/nlme/html/gls.html (archived at https://perma.cc/RHZ6-5GT8)
- Regression with cluster variable
- `robcov()` from `rms` package
- [Hierarchical linear modeling](hlm.html)
- [Linear mixed effects models](hlm.html#linear)
- [Generalized linear mixed effects models](hlm.html#generalized)
- [Nonlinear mixed effects models](hlm.html#nonlinear)
### 5. No multicollinearity
Multicollinearity occurs when the predictors are correlated with each other.
#### Ways to Test
- Variance Inflation Factor (VIF)
- Generalized Variance Inflation Factor (GVIF)—when models have related regressors (multiple polynomial terms or contrasts from same predictor)
- Correlation
- Tolerance
- Condition Index
##### Variance Inflation Factor (VIF)
$$
\text{VIF} = 1/\text{Tolerance}
$$
If the variance inflation factor of a predictor variable were 5.27 ($\sqrt{5.27} = 2.3$), this means that the standard error for the coefficient of that predictor variable is 2.3 times as large (i.e., confidence interval is 2.3 times wider) as it would be if that predictor variable were uncorrelated with the other predictor variables.
VIF = 1: Not correlated\
1 < VIF < 5: Moderately correlated\
VIF > 5 to 10: Highly correlated (multicollinearity present)
```{r}
vif(multipleRegressionModel)
```
##### Generalized Variance Inflation Factor (GVIF)
Useful when models have related regressors (multiple polynomial terms or contrasts from same predictor)
##### Correlation
correlation among all independent variables the correlation coefficients should be smaller than .08
```{r}
cor(
mydata[,c("bpi_antisocialT1Sum","bpi_anxiousDepressedSum")],
use = "pairwise.complete.obs")
```
##### Tolerance
The tolerance is an index of the influence of one independent variable on all other independent variables.
$$
\text{tolerance} = 1/\text{VIF}
$$
T < 0.2: there might be multicollinearity in the data\
T < 0.01: there certainly is multicollinarity in the data