-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy path11_LinearRegression.Rmd
2449 lines (1787 loc) · 80.5 KB
/
11_LinearRegression.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
```{r include=FALSE, cache=FALSE}
set.seed(42)
options(digits = 3)
library(tidyverse)
library(knitr)
knitr::opts_chunk$set(
comment = "#>",
messages = FALSE,
collapse = TRUE,
out.width = "85%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold"
)
options(dplyr.print_min = 6, dplyr.print_max = 6)
```
```{r, echo=FALSE}
library(knitr)
hook_output <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
lines <- options$output.lines
if (is.null(lines)) {
return(hook_output(x, options)) # pass to default hook
}
x <- unlist(strsplit(x, "\n"))
more <- "etc ..."
if (length(lines)==1) { # first n lines
if (length(x) > lines) { # truncate the output, but add ....
x <- c(head(x, lines), more)
}
} else {
x <- c(more, x[lines], more)
}
# paste these lines together
x <- paste(c(x, ""), collapse = "\n")
hook_output(x, options)
})
```
```{r, include=FALSE}
library(tidyverse)
```
# Linear Regression and ANOVA {#LinearRegressionAndANOVA}
Introduction {-#intro-LinearRegressionAndANOVA}
------------
In statistics, modeling is where we get down to business. Models
quantify the relationships between our variables. Models let us make
predictions.
A simple linear regression is the most basic model. It’s just two
variables and is modeled as a linear relationship with an error term:
> *y*~*i*~ = *β*~0~ + *β*~1~*x*~*i*~ + *ε*~*i*~
We are given the data for *x* and *y*. Our mission is to fit the model,
which will give us the best estimates for *β*~0~ and *β*~1~
(see Recipe \@ref(recipe-id203), ["Performing Simple Linear Regression"](#recipe-id203)).
That generalizes naturally to multiple linear regression, where we have
multiple variables on the righthand side of the relationship
(see Recipe \@ref(recipe-id203), ["Performing Multiple Linear Regression"](#recipe-id204)):
> *y*~*i*~ = *β*~0~ + *β*~1~*u*~*i*~ + *β*~2~*v*~*i*~ + *β*~3~*w*~*i*~ +
> *ε*~*i*~
Statisticians call *u*, *v*, and *w* the *predictors* and *y* the
*response*. Obviously, the model is useful only if there is a fairly
linear relationship between the predictors and the response, but that
requirement is much less restrictive than you might think.
Recipe \@ref(recipe-id203), ["Regressing on Transformed Data"](#recipe-id208), discusses transforming
your variables into a (more) linear relationship so that you can use the
well-developed machinery of linear regression.
The beauty of R is that anyone can build these linear models. The models
are built by a function, `lm`, which returns a model object. From the
model object, we get the coefficients (*β*~*i*~) and regression
statistics. It’s easy. Really!
The horror of R is that anyone can build these models. Nothing requires
you to check that the model is reasonable, much less statistically
significant. Before you blindly believe a model, check it. Most of the
information you need is in the regression summary
(see Recipe \@ref(recipe-id203), ["Understanding the Regression Summary"](#recipe-id240)):
Is the model statistically significant?
: Check the *F* statistic at the bottom of the summary.
Are the coefficients significant?
: Check the coefficient’s *t* statistics and *p*-values in the
summary, or check their confidence intervals
(see Recipe \@ref(recipe-id203), ["Forming Confidence Intervals for Regression"](#recipe-id211)).
Is the model useful?
: Check the *R*^2^ near the bottom of the summary.
Does the model fit the data well?
: Plot the residuals and check the regression diagnostics (see Recipes \@ref(recipe-id203), ["Plotting Regression Residuals"](#recipe-id216), and \@ref(recipe-id203), ["Diagnosing a Linear Regression"](#recipe-id212)).
Does the data satisfy the assumptions behind linear regression?
: Check whether the diagnostics confirm that a linear model is
reasonable for your data
(see Recipe \@ref(recipe-id203), ["Diagnosing a Linear Regression"](#recipe-id212)).
### ANOVA {-}
Analysis of variance (ANOVA) is a powerful statistical technique.
First-year graduate students in statistics are taught ANOVA almost
immediately because of its importance, both theoretical and practical.
We are often amazed, however, at the extent to which people outside the
field are unaware of its purpose and value.
Regression creates a model, and ANOVA is one method of evaluating such
models. The mathematics of ANOVA are intertwined with the mathematics of
regression, so statisticians usually present them together; we follow
that tradition here.
ANOVA is actually a family of techniques that are connected by a common
mathematical analysis. This chapter mentions several applications:
One-way ANOVA
: This is the simplest application of ANOVA. Suppose you have data
samples from several populations and are wondering whether the
populations have different means. One-way ANOVA answers
that question. If the populations have normal distributions, use the
`oneway.test` function (see Recipe \@ref(recipe-id203), ["Performing One-Way ANOVA"](#recipe-id218));
otherwise, use the nonparametric version, the `kruskal.test`
function
(see Recipe \@ref(recipe-id203), ["Performing Robust ANOVA (Kruskal–Wallis Test")](#recipe-id228)).
Model comparison
: When you add or delete a predictor variable from a linear
regression, you want to know whether that change did or did not
improve the model. The `anova` function compares two regression
models and reports whether they are significantly different
(see Recipe \@ref(recipe-id203), ["Comparing Models by Using ANOVA"](#recipe-id232)).
ANOVA table
: The `anova` function can also construct the ANOVA table of a linear
regression model, which includes the *F* statistic needed to gauge
the model’s statistical significance
(see Recipe \@ref(recipe-id203), ["Getting Regression Statistics"](#recipe-id231)). This important
table is discussed in nearly every textbook on regression.
The See Also section contains more about the mathematics of ANOVA.
### Example Data {-}
In many of the examples in this chapter, we start with creating example data using R's pseudorandom number generation capabilities. So at the beginning of each recipe, you may see something like the following:
```{r}
set.seed(42)
x <- rnorm(100)
e <- rnorm(100, mean=0, sd=5)
y <- 5 + 15 * x + e
```
We use `set.seed` to set the random number generation seed so that if you run the example code on your machine you will get the same answer. In the preceding example, `x` is a vector of 100 draws from a standard normal (`mean` = 0, `sd` = 1) distribution. Then we create a little random noise called `e` from a normal distribution with `mean` = 0 and `sd` = 5. `y` is then calculated as `5 + 15 * x + e`. The idea behind creating example data rather than using "real world" data is that with simulated "toy" data you can change the coefficients and parameters and see how the change impacts the resulting model. For example, you could increase the standard deviation of `e` in the example data and see what impact that has on the `R^2` of your model.
### See Also {-}
There are many good texts on linear regression. One of our favorites is
*Applied Linear Regression Models*, 4th edition, by Michael Kutner, Christopher Nachtsheim, and John Neter (McGraw-Hill/Irwin). We generally follow their terminology and
conventions in this chapter.
We also like *Linear Models with R* by Julian Faraway (Chapman & Hall),
because it illustrates regression using R and is quite readable.
Earlier versions of Faraday's work are available free [online](http://cran.r-project.org/doc/contrib/Faraway-PRA.pdf), too.
Performing Simple Linear Regression {#recipe-id203}
-----------------------------------
### Problem {-#problem-id203}
You have two vectors, *x* and *y*, that hold paired observations:
(*x*~1~, *y*~1~), (*x*~2~, *y*~2~), ..., (*x~n~*, *y~n~*). You believe
there is a linear relationship between *x* and *y*, and you want to
create a regression model of the relationship.
### Solution {-#solution-id203}
The `lm` function performs a linear regression and reports the
coefficients.
If your data is in vectors:
```{r, eval=FALSE}
lm(y ~ x)
```
Or if your data is in columns in a data frame:
```{r, eval=FALSE}
lm(y ~ x, data = df)
```
### Discussion {-#discussion-id203}
Simple linear regression involves two variables: a predictor (or independent) variable,
often called *x*, and a response (or dependent) variable, often called *y*. The
regression uses the *ordinary least-squares* (OLS) algorithm to fit the
linear model:
> *y~i~* = *β*~0~ + *β*~1~*x~i~* + *ε~i~*
where *β*~0~ and *β*~1~ are the regression coefficients and the *ε~i~*
are the error terms.
The `lm` function can perform linear regression. The main argument is a
model formula, such as `y ~ x`. The formula has the response variable on
the left of the tilde character (`~`) and the predictor variable on the
right. The function estimates the regression coefficients, *β*~0~ and
*β*~1~, and reports them as the intercept and the coefficient of *x*,
respectively:
``` {r}
set.seed(42)
x <- rnorm(100)
e <- rnorm(100, mean = 0, sd = 5)
y <- 5 + 15 * x + e
lm(y ~ x)
```
In this case, the regression equation is:
> *y~i~* = 4.56 + 15.14*x~i~* + *ε~i~*
It is quite common for data to be captured inside a data frame, in which
case you want to perform a regression between two data frame columns.
Here, `x` and `y` are columns of a data frame `dfrm`:
``` {r}
df <- data.frame(x, y)
head(df)
```
The `lm` function lets you specify a data frame by using the `data`
parameter. If you do, the function will take the variables from the data
frame and not from your workspace:
``` {r}
lm(y ~ x, data = df) # Take x and y from df
```
Performing Multiple Linear Regression {#recipe-id204}
-------------------------------------
### Problem {-#problem-id204}
You have several predictor variables (e.g., *u*, *v*, and *w*) and a
response variable, *y*. You believe there is a linear relationship
between the predictors and the response, and you want to perform a
linear regression on the data.
### Solution {-#solution-id204}
Use the `lm` function. Specify the multiple predictors on the righthand
side of the formula, separated by plus signs (`+`):
``` {r, eval=FALSE}
lm(y ~ u + v + w)
```
### Discussion {-#discussion-id204}
Multiple linear regression is the obvious generalization of simple
linear regression. It allows multiple predictor variables instead of one
predictor variable and still uses OLS to compute the coefficients of a
linear equation. The three-variable regression just given corresponds to
this linear model:
> *y~i~* = *β*~0~ + *β*~1~*u~i~* + *β*~2~*v~i~* + *β*~3~*w~i~* + *ε~i~*
R uses the `lm` function for both simple and multiple linear regression.
You simply add more variables to the righthand side of the model
formula. The output then shows the coefficients of the fitted model. Let's set up some example random normal data using the `rnorm` function:
``` {r}
set.seed(42)
u <- rnorm(100)
v <- rnorm(100, mean = 3, sd = 2)
w <- rnorm(100, mean = -3, sd = 1)
e <- rnorm(100, mean = 0, sd = 3)
```
Then we can create an equation using known coefficients to calculate our *y* variable:
```{r}
y <- 5 + 4 * u + 3 * v + 2 * w + e
```
And then if we run a linear regression, we can see that R solves for the coefficients and gets pretty close to the actual values just used:
```{r}
lm(y ~ u + v + w)
```
The `data` parameter of `lm` is especially valuable when the number of
variables increases, since it’s much easier to keep your data in one
data frame than in many separate variables. Suppose your data is
captured in a data frame, such as the `df` variable shown here:
``` {r}
df <- data.frame(y, u, v, w)
head(df)
```
When we supply `df` to the `data` parameter of `lm`, R looks for the
regression variables in the columns of the data frame:
``` {r}
lm(y ~ u + v + w, data = df)
```
### See Also {-#see_also-id204}
See Recipe \@ref(recipe-id203), ["Performing Simple Linear Regression"](#recipe-id203), for simple
linear regression.
Getting Regression Statistics {#recipe-id231}
-----------------------------
### Problem {-#problem-id231}
You want the critical statistics and information regarding your
regression, such as *R*^2^, the *F* statistic, confidence intervals for
the coefficients, residuals, the ANOVA table, and so forth.
### Solution {-#solution-id231}
Save the regression model in a variable, say `m`:
``` {r}
m <- lm(y ~ u + v + w)
```
Then use functions to extract regression statistics and information from
the model:
`anova(m)`
: ANOVA table
`coefficients(m)`
: Model coefficients
`coef(m)`
: Same as `coefficients(m)`
`confint(m)`
: Confidence intervals for the regression coefficients
`deviance(m)`
: Residual sum of squares
`effects(m)`
: Vector of orthogonal effects
`fitted(m)`
: Vector of fitted *y* values
`residuals(m)`
: Model residuals
`resid(m)`
: Same as `residuals(m)`
`summary(m)`
: Key statistics, such as *R*^2^, the *F* statistic, and the residual
standard error (*σ*)
`vcov(m)`
: Variance–covariance matrix of the main parameters
### Discussion {-#discussion-id231}
When we started using R, the documentation said use the `lm` function to
perform linear regression. So we did something like this, getting the
output shown in Recipe \@ref(recipe-id204), ["Performing Multiple Linear Regression"](#recipe-id204):
``` {r}
lm(y ~ u + v + w)
```
How disappointing! The output was nothing compared to other
statistics packages such as SAS. Where is *R*^2^? Where are the
confidence intervals for the coefficients? Where is the *F* statistic,
its *p*-value, and the ANOVA table?
Of course, all that information is available—you just have to ask for
it. Other statistics systems dump everything and let you wade through
it. R is more minimalist. It prints a bare-bones output and lets you
request what more you want.
The `lm` function returns a model object that you can assign to a
variable:
``` {r}
m <- lm(y ~ u + v + w)
```
From the model object, you can extract important information using
specialized functions. The most important function is `summary`:
``` {r}
summary(m)
```
The summary shows the estimated coefficients. It shows the critical
statistics, such as *R*^2^ and the *F* statistic. It shows an estimate
of *σ*, the standard error of the residuals. The summary is so important
that there is an entire recipe devoted to understanding it. See also Recipe \@ref(recipe-id240), ["Understanding the Regression Summary"](#recipe-id240).
There are specialized extractor functions for other important
information:
Model coefficients (point estimates)
:
``` {r}
coef(m)
```
Confidence intervals for model coefficients
:
``` {r}
confint(m)
```
Model residuals
:
``` {r}
resid(m)
```
Residual sum of squares
:
``` {r}
deviance(m)
```
ANOVA table
:
``` {r}
anova(m)
```
If you find it annoying to save the model in a variable, you are welcome
to use one-liners such as this:
``` {r, eval=FALSE}
summary(lm(y ~ u + v + w))
```
Or you can use `magritr` pipes:
``` {r, eval=FALSE}
lm(y ~ u + v + w) %>%
summary
```
### See Also {-#see_also-id231}
See Recipe \@ref(recipe-id240), ["Understanding the Regression Summary"](#recipe-id240). See Recipe \@ref(recipe-id233), ["Identifying Influential Observations"](#recipe-id233), for regression statistics specific to model diagnostics.
Understanding the Regression Summary {#recipe-id240}
------------------------------------
### Problem {-#problem-id240}
You created a linear regression model, `m`. However, you are confused by
the output from `summary(m)`.
### Discussion {-#discussion-id240}
The model summary is important because it links you to the most critical
regression statistics. Here is the model summary from Recipe \@ref(recipe-id231), ["Getting Regression Statistics"](#recipe-id231):
``` {r}
summary(m)
```
Let’s dissect this summary by section. We’ll read it from top to
bottom—even though the most important statistic, the *F* statistic,
appears at the end.
Call
:
```
summary(m)$call
#> lm(formula = y ~ u + v + w)
```
This shows how `lm` was called when it created the model, which is
important for putting this summary into the proper context.
Residuals statistics
:
```
#> Residuals:
#> Min 1Q Median 3Q Max
#> -5.383 -1.760 -0.312 1.856 6.984
```
Ideally, the regression residuals would have a perfect
normal distribution. These statistics help you identify possible
deviations from normality. The OLS algorithm is mathematically
guaranteed to produce residuals with a mean of zero.[^zeromean] Hence the
sign of the median indicates the skew’s direction, and the magnitude
of the median indicates the extent. In this case the median is
negative, which suggests some skew to the left.
If the residuals have a nice, bell-shaped distribution, then the
first quartile (`1Q`) and third quartile (`3Q`) should have about the
same magnitude. In this example, the larger magnitude of `3Q` versus
`1Q` (1.859 versus 1.76) indicates a slight skew to the right in
our data, although the negative median makes the situation
less clear-cut.
The `Min` and `Max` residuals offer a quick way to detect extreme
outliers in the data, since extreme outliers (in the
response variable) produce large residuals.
Coefficients
:
```
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 4.770 0.969 4.92 3.5e-06 ***
#> u 4.173 0.260 16.07 < 2e-16 ***
#> v 3.013 0.148 20.31 < 2e-16 ***
#> w 1.905 0.266 7.15 1.7e-10 ***
```
The column labeled `Estimate` contains the estimated regression
coefficients as calculated by ordinary least squares.
Theoretically, if a variable’s coefficient is zero then the variable
is worthless; it adds nothing to the model. Yet the coefficients
shown here are only estimates, and they will never be exactly zero.
We therefore ask: Statistically speaking, how likely is it that the
true coefficient is zero? That is the purpose of the *t* statistics
and the *p*-values, which in the summary are labeled (respectively)
`t` `value` and `Pr(>|t|)`.
The *p*-value is a probability. It gauges the likelihood that the
coefficient is *not* significant, so smaller is better. Big is bad
because it indicates a high likelihood of insignificance. In this
example, the *p*-value for the *u* coefficient is a mere 0.00106, so
*u* is likely significant. The *p*-value for *w*, however, is
0.05744; this is just over our conventional limit of 0.05, which
suggests that *w* is likely insignificant.[^significant] Variables with large
*p*-values are candidates for elimination.
A handy feature is that R flags the significant variables for
quick identification. Do you notice the extreme righthand column
containing double asterisks (`**`), a single asterisk (`*`), and a
period(`.`)? That column highlights the significant variables. The
line labeled `Signif. codes` at the bottom gives a cryptic guide
to the flags’ meanings:
--------- ----------------------------------
`***` *p*-value between 0 and 0.001
`**` *p*-value between 0.001 and 0.01
`*` *p*-value between 0.01 and 0.05
`.` *p*-value between 0.05 and 0.1
(blank) *p*-value between 0.1 and 1.0
--------- ----------------------------------
The column labeled `Std.` `Error` is the standard error of the
estimated coefficient. The column labeled `t` `value` is the *t*
statistic from which the *p*-value was calculated.
Residual standard error
:
``` {r}
# Residual standard error: 2.66 on 96 degrees of freedom
```
This reports the standard error of the residuals (*σ*)—that is, the
sample standard deviation of *ε*.
*R*^2^ (coefficient of determination)
:
```
# Multiple R-squared: 0.885, Adjusted R-squared: 0.882
```
*R*^2^ is a measure of the model’s quality. Bigger is better.
Mathematically, it is the fraction of the variance of *y* that is
explained by the regression model. The remaining variance is not
explained by the model, so it must be due to other factors (i.e.,
unknown variables or sampling variability). In this case, the model
explains 0.885 (88.5%) of the variance of *y*, and the remaining
0.115 (11.5%) is unexplained.
That being said, we strongly suggest using the adjusted rather than
the basic *R*^2^. The adjusted value accounts for the number of
variables in your model and so is a more realistic assessment of
its effectiveness. In this case, then, we would use 0.882,
not 0.885.
*F* statistic
:
```
# F-statistic: 246.6 on 3 and 96 DF, p-value: < 2.2e-16
```
The *F* statistic tells you whether the model is significant
or insignificant. The model is significant if any of the
coefficients are nonzero (i.e., if *β*~*i*~ ≠ 0 for some *i*). It is
insignificant if all coefficients are zero (*β*~1~ = *β*~2~ = … =
*β*~*n*~ = 0).
Conventionally, a *p*-value of less than 0.05 indicates that the
model is likely significant (one or more *β*~*i*~ are nonzero),
whereas values exceeding 0.05 indicate that the model is likely
not significant. Here, the probability is only 2.2e-16 that our
model is insignificant. That’s good.
Most people look at the *R*^2^ statistic first. The statistician
wisely starts with the *F* statistic, because if the model is not
significant then nothing else matters.
### See Also {-#see_also-id240}
See Recipe \@ref(recipe-id231), ["Getting Regression Statistics"](#recipe-id231), for more on
extracting statistics and information from the model object.
Performing Linear Regression Without an Intercept {#recipe-id205}
-------------------------------------------------
### Problem {-#problem-id205}
You want to perform a linear regression, but you want to force the
intercept to be zero.
### Solution {-#solution-id205}
Add "`+` `0`" to the righthand side of your regression formula. That
will force `lm` to fit the model with a zero intercept:
``` {r, eval=FALSE}
lm(y ~ x + 0)
```
The corresponding regression equation is:
> *y*~*i*~ = *βx*~*i*~ + *ε*~*i*~
### Discussion {-#discussion-id205}
Linear regression ordinarily includes an intercept term, so that is the
default in R. In rare cases, however, you may want to fit the data while
assuming that the intercept is zero. In this case you make a modeling
assumption: when *x* is zero, *y* should be zero.
When you force a zero intercept, the `lm` output includes a coefficient
for *x* but no intercept for *y*, as shown here:
``` {r}
lm(y ~ x + 0)
```
We strongly suggest you check that modeling assumption before proceeding.
Perform a regression with an intercept; then see if the intercept could
plausibly be zero. Check the intercept’s confidence interval. In this
example, the confidence interval is (6.26, 8.84):
``` {r}
confint(lm(y ~ x))
```
Because the confidence interval does not contain zero, it is *not* statistically
plausible that the intercept could be zero. So in this case, it is not reasonable to rerun the regression while forcing a zero intercept.
Regressing Only Variables That Highly Correlate with Your Dependent Variable {#title-highcor}
------------------------------------------------------
### Problem {-#problem-highcor}
You have a data frame with many variables and you want to build a multiple linear regression using only the variables that are highly correlated to your response (dependent) variable.
### Solution {-#solution-highcor}
If `df` is our data frame containing both our response (dependent) and all our predictor (independent) variables and `dep_var` is our response variable, we can figure out our best predictors and then use them in a linear regression. If we want the top four predictor variables, we can use this recipe:
```{r, eval=FALSE}
best_pred <- df %>%
select(-dep_var) %>%
map_dbl(cor, y = df$dep_var) %>%
sort(decreasing = TRUE) %>%
.[1:4] %>%
names %>%
df[.]
mod <- lm(df$dep_var ~ as.matrix(best_pred))
```
This recipe is a combination of many different pieces of logic used elsewhere in this book. We will describe each step here, and then walk through it in the Discussion using some example data.
First we drop the response variable out of our pipe chain so that we have only our predictor variables in our data flow:
```{r, eval=FALSE}
df %>%
select(-dep_var)
```
Then we use `map_dbl` from `purrr` to perform a pairwise correlation on each column relative to the response variable:
```{r, eval=FALSE}
map_dbl(cor, y = df$dep_var) %>%
```
We then take the resulting correlations and sort them in decreasing order:
```{r, eval=FALSE}
sort(decreasing = TRUE) %>%
```
We want only the top four correlated variables, so we select the top four records in the resulting vector:
```{r, eval=FALSE}
.[1:4] %>%
```
And we don't need the correlation values, only the names of the rows—which are the variable names from our original data frame, `df`:
```{r, eval=FALSE}
names %>%
```
Then we can pass those names into our subsetting brackets to select only the columns with names matching the ones we want:
```{r, eval=FALSE}
df[.]
```
Our pipe chain assigns the resulting data frame into `best_pred`. We can then use `best_pred` as the predictor variables in our regression and we can use `df$dep_var` as the response:
```{r, eval=FALSE}
mod <- lm(df$dep_var ~ as.matrix(best_pred))
```
### Discussion {-#discussion-title}
By combining the mapping functions discussed in Recipe \@ref(recipe-id157), ["Applying a Function to Every Column"](#recipe-id157), we can create a recipe to remove low-correlation variables from
a set of predictors and use the high-correlation predictors in a regression.
We have an example data frame that contains six predictor variables named `pred1` through `pred6`. The response variable is named `resp`. Let's walk that data frame through our logic and see how it works.
Loading the data and dropping the `resp` variable is pretty straightforward. So let's look at the result of mapping the `cor` function:
```{r}
# loads the pred data frame
load("./data/pred.rdata")
pred %>%
select(-resp) %>%
map_dbl(cor, y = pred$resp)
```
The output is a named vector of values where the names are the variable names and the values are the pairwise correlations between each predictor variable and `resp`, the response variable.
If we sort this vector, we get the correlations in decreasing order:
```{r}
pred %>%
select(-resp) %>%
map_dbl(cor, y = pred$resp) %>%
sort(decreasing = TRUE)
```
Using subsetting allows us to select the top four records. The `.` operator is a special operator that tells the pipe where to put the result of the prior step.
```{r}
pred %>%
select(-resp) %>%
map_dbl(cor, y = pred$resp) %>%
sort(decreasing = TRUE) %>%
.[1:4]
```
We then use the `names` function to extract the names from our vector. The names are the names of the columns we ultimately want to use as our independent variables:
```{r}
pred %>%
select(-resp) %>%
map_dbl(cor, y = pred$resp) %>%
sort(decreasing = TRUE) %>%
.[1:4] %>%
names
```
When we pass the vector of names into `pred[.]`, the names are used to select columns from the `pred` data frame. We then use `head` to select only the top six rows for easier illustration:
```{r}
pred %>%
select(-resp) %>%
map_dbl(cor, y = pred$resp) %>%
sort(decreasing = TRUE) %>%
.[1:4] %>%
names %>%
pred[.] %>%
head
```
Now let's bring it all together and pass the resulting data into the regression:
```{r}
best_pred <- pred %>%
select(-resp) %>%
map_dbl(cor, y = pred$resp) %>%
sort(decreasing = TRUE) %>%
.[1:4] %>%
names %>%
pred[.]
mod <- lm(pred$resp ~ as.matrix(best_pred))
summary(mod)
```
Performing Linear Regression with Interaction Terms {#recipe-id206}
---------------------------------------------------
### Problem {-#problem-id206}
You want to include an interaction term in your regression.
### Solution {-#solution-id206}
The R syntax for regression formulas lets you specify interaction terms.
To indicate the interaction of two variables, `u` and `v`, we separate their names with an asterisk (`*`):
``` {r, eval=FALSE}
lm(y ~ u * v)
```
This corresponds to the model *y*~i~ = *β*~0~ + *β*~1~*u*~*i*~ +
*β*~2~*v*~*i*~ + *β*~3~*u*~*i*~*v*~*i*~ + *ε*~*i*~, which includes the
first-order interaction term *β*~3~*u*~*i*~*v*~*i*~.
### Discussion {-#discussion-id206}
In regression, an interaction occurs when the product of two predictor
variables is also a significant predictor (i.e., in addition to the
predictor variables themselves). Suppose we have two predictors, *u* and
*v*, and want to include their interaction in the regression. This is
expressed by the following equation:
> *y*~*i*~ = *β*~0~ + *β*~1~*u*~*i*~ + *β*~2~*v*~*i*~ +
> *β*~3~*u*~*i*~*v*~*i*~ + *ε*~*i*~
Here the product term, *β*~3~*u*~*i*~*v*~*i*~, is called the *interaction
term*. The R formula for that equation is:
``` {r, eval=FALSE}
y ~ u * v
```
When you write `y` `~` `u * v`, R automatically includes *u*, *v*, and
their product in the model. This is for a good reason. If a model
includes an interaction term, such as *β*~3~*u*~*i*~*v*~*i*~, then
regression theory tells us the model should also contain the constituent
variables *u*~*i*~ and *v*~*i*~.
Likewise, if you have three predictors (*u*, *v*, and *w*) and want to
include all their interactions, separate them by asterisks:
``` {r, eval=FALSE}
y ~ u * v * w
```
This corresponds to the regression equation:
> *y*~*i*~ = *β*~0~ + *β*~1~*u*~*i*~ + *β*~2~*v*~*i*~ + *β*~3~*w*~*i*~ +
> *β*~4~*u*~*i*~*v*~*i*~ + *β*~5~*u*~*i*~*w*~*i*~ +
> *β*~6~*v*~*i*~*w*~*i*~ + *β*~7~*u*~*i*~*v*~*i*~*w*~*i*~ + *ε*~*i*~
Now we have all the first-order interactions and a second-order
interaction (*β*~7~*u*~*i*~*v*~*i*~*w*~*i*~).
Sometimes, however, you may not want every possible interaction. You can
explicitly specify a single product by using the colon operator (`:`).
For example, `u:v:w` denotes the product term *βu*~*i*~*v*~*i*~*w*~*i*~
but without all possible interactions. So the R formula:
``` {r, eval=FALSE}
y ~ u + v + w + u:v:w
```
corresponds to the regression equation:
> *y*~*i*~ = *β*~0~ + *β*~1~*u*~*i*~ + *β*~2~*v*~*i*~ + *β*~3~*w*~*i*~ +
> *β*~4~*u*~*i*~*v*~*i*~*w*~*i*~ + *ε*~*i*~
It might seem odd that colon (`:`) means pure multiplication while
asterisk (`*`) means both multiplication and inclusion of constituent
terms. Again, this is because we normally incorporate the constituents
when we include their interaction, so making that approach the default for
asterisk makes sense.
There is some additional syntax for easily specifying many interactions:
`(u + v + ... + w)^2`
: Include all variables (*u*, *v*, ..., *w*) and all their
first-order interactions.
`(u + v + ... + w)^3`
: Include all variables, all their first-order interactions, and all
their second-order interactions.
`(u + v + ... + w)^4`
: And so forth.
Both the asterisk (`*`) and the colon (`:`) follow a “distributive law,”
so the following notations are also allowed:
`x*(u + v + ... + w)`
: Same as `x*u + x*v + ... +
x*w`
(which is the same as `x +
u + v + ... + w + x:u + x:v + ... + x:w`).
`x:(u + v + ... + w)`
: Same as `x:u + x:v + ... + x:w`.
All this syntax gives you some flexibility in writing your formula. For
example, these three formulas are equivalent:
``` {r, eval=FALSE}
y ~ u * v
y ~ u + v + u:v
y ~ (u + v) ^ 2
```
They all define the same regression equation, *y*~*i*~ = *β*~0~ +
*β*~1~*u*~*i*~ + *β*~2~*v*~*i*~ + *β*~3~*u*~*i*~*v*~*i*~ + *ε*~*i*~ .
### See Also {-#see_also-id206}
The full syntax for formulas is richer than described here.
See [*R in a Nutshell*](http://oreilly.com/catalog/9780596801717) (O’Reilly)
or the R Language Definition for more details.
Selecting the Best Regression Variables {#recipe-id236}
---------------------------------------
### Problem {-#problem-id236}
You are creating a new regression model or improving an existing model.
You have the luxury of many regression variables, and you want to select
the best subset of those variables.