---
title: "STAT 224 Chapter 5"
output:
  html_document:
    theme: cerulean
    css: styles.css
    code_folding: hide
    df_print: kable
    number_sections: yes
    self_contained: yes
    toc_depth: 3
    toc_float: 
      collapsed: false
  pdf_document:
    toc: yes
params:
  dotabs:  TRUE
    
---

```{r test-main, child = 'preamble.Rmd'}
```


# Chapter 5: Categorical Variables as Predictors `r if(params$dotabs) paste('{.tabset}')`
## Lecture 8

### Intro

So far... predictor variables quantitative

#### What's new...  categorical predictors

Not all potential predictors need to be measured on a continuous numeric scale. 

Categorical variables include numeric and non-numeric variables   
usually with just a few possible values:

  + education level (high school, some college, college degree, grad school)
  + gender (male, female)
  + number of siblings (0, 1, 2, 3, ..., some smallish number)
  + management style (delegator, micromanager, somewhere in between)
  + preferences (very low, low, neutral, high, very high)
  + job type (unskilled, skilled, white collar, management, executive)
  + furniture color (blue, brown, black, white)
  + marital status (single, married, widowed, divorced)
  + age group (youth, young adult, middle-aged, elderly)
  + race/ethnicity (black, hispanic, white, other)
  
##### Ordinal vs. nominal categorical variables
  
Categorical variables are **ordinal** or **nominal**

ordinal variables: categories have a natural ordering

  + education level
  + number of siblings (this even has natural numerical values: 0, 1, 2, ...)
  + preferences
  + job type
  + age group
  + management style
  
nominal variables: no ordering

  + gender
  + furniture color
  + marital status
  + race/ethnicity

##### Indicator variables

Linear regression requires minimization of a function of numeric values.

So, we need to recode the categories as numbers   
in order to include a categorical variable in the regression.

A categorical variable can be represented by one or more **indicator variables**.

Indicator variables...

  + "indicate" the presence or absence of a given feature, 
  + encoded using two values, usually 1 (feature present) and 0 (feature absent), 
  
For example, 
\[
\mbox{gender} = \left\{ \begin{array}{l}
	    0 & \mbox{if female} \\
	    1 & \mbox{if male}
	    \end{array} \right.
\]

Indicator variables are sometimes called "dummy variables"    
since they are not the actual predictor variable, but a representation of the variable.

...like crash car dummies are not real people, but represent us in crash tests.  :)

###### Why indicate using 0's and 1's?

Ease of interpretation.

Example:

$Y =$ annual salary   
$x_1 =$ gender (male = 1, female = 0)   
$x_2 =$ years of experience

$$Y = \beta_0 + \beta_1\, x_1 
+ \beta_2\, x_2 +  \epsilon$$


Among females, $x_1 = 0$ and    
$$E(Y \mid x_1, x_2) = \beta_0 + \beta_1 (0) + \beta_2\, x_2 = \beta_0 + \beta_2\, x_2$$

Among males, $x_1 = 1$ and     
$$E(Y \mid x_1, x_2) = \beta_0 + \beta_1 (1) + \beta_2\, x_2 = (\beta_0 + \beta_1) + \beta_2\, x_2$$

What does $\beta_0$ mean?

Females ($x_1=0$) with no experience ($x_2=0$) can expect to earn $\beta_0$ per year    
$\beta_0$ = the base salary for females.

What does $\beta_1$ mean?

Males ($x_1=0$) with no experience ($x_2=0$) can expect to earn $(\beta_0 + \beta_1)$ per year.    
$\beta_0 + \beta_1$ = the base salary for males.    
$\beta_1$ = the difference in base salary for men vs. women.

$\beta_1$ is also the average difference in salary for men    
among men and women with the same experience level.

<br><br>

We could code gender 
\[
x_1 = \mbox{gender} = \left\{ \begin{array}{l}
	    1 & \mbox{if male} \\
	    2 & \mbox{if female}
	    \end{array} \right.
\]

But, then the average salary for females with no experience   
is $\beta_0 + 2\beta_1$ and the coefficients get harder to interpret.

### More Details

#### SLR with a categorical predictor

We want to predict some quantity $Y$ with gender (male, female)   
As we will see, this is tantamount to comparing the means between the two groups.

We could write the model as
\[
\E(Y \mid \mbox{gender}) \;=\; \beta_0 + \beta_1\, x \;=\; \beta_0 + \beta_1\, \mbox{gender} 
\]

where

\[
\mbox{gender} = \left\{ \begin{array}{l}
	    0 & \mbox{if female} \\
	    1 & \mbox{if male}
	    \end{array} \right.
\]

Recall that the meaning of $\beta_0$ is $\E(Y \mid x=0)$.    
So, $\beta_0$ is the mean of $Y$ for females. 

What is $\beta_1$?

<br><br><br><br><br><br><br><br><br><br>

For men, $\E(Y \mid \mbox{gender}) = \beta_0 + \beta_1 (1) = \beta_0 + \beta_1$

As always in SLR, $\beta_1$ is the change in the mean of $Y$   
associated with a one unit increase in $x$.

Thus, $\beta_1$ is the shift, change, ...or difference in the mean   
for gender=1 (male) vs. gender=0 (female):

$\beta_1 = \mu_{\rm male} - \mu_{\rm female}$

So, the test of $\beta_1 = 0$ is equivalent to   
testing "no difference in the mean" due to group membership (male vs. female).

That is, all of the following hypotheses are equivalent:

  + $H_0: \beta_1 = 0$
  + $H_0: \mu_{\rm male} - \mu_{\rm female} = 0$
  + $H_0: \mu_{\rm male} = \mu_{\rm female}$
  
The last two hypotheses you might recognize can be tested   
using the two-sample (pooled-variance) t-test

Why the pooled-variance test?   
Because in regression model requires constant variance for all $x$ values.    
...and would it even make sense to compare the means if the variances were quite different?

So, if the regression assumptions hold, then $\var(Y) = \sigma^2$   
for both men (gender=1) and women (gender=0).

The pooled-variance two-sample t-test has $n_1 + n_2 -2 = n-2$ degrees of freedom   
...the same as when testing $H_0: \beta_1 = 0$

And, yes, the two test statistics are algebraically equivalent:

$$t = \frac{\b1}{\se(\b1)} 
\;=\; \frac{\ybar_{\rm male} - \ybar_{\rm female}}{\displaystyle s_p \sqrt{\frac{1}{n_1} + \frac{1}{n_2}}}$$

**Note:**
$\ybar_{\rm male}$ and $\ybar_{\rm female}$ are the least squares estimates for $\mu_{\rm male}$ and $\mu_{\rm female}$, respectively.

##### Why only one indicator variable for predictor with two levels?

Why not set up the following model?

\[
\E(Y \mid \mbox{gender}) 
\;=\; \beta_0 + \beta_1\, x_1 + \beta_1\, x_2 
\;=\; \beta_0 + \beta_1(\mbox{genderMale}) + \beta_1(\mbox{genderFemale})
\]

where

\[
\mbox{genderMale} = \left\{ \begin{array}{l}
	    0 & \mbox{if female} \\
	    1 & \mbox{if male}
	    \end{array} \right.
\]

and

\[
\mbox{genderFemale} = \left\{ \begin{array}{l}
	    0 & \mbox{if male} \\
	    1 & \mbox{if female}
	    \end{array} \right.
\]

**Two problems:**

  1. What is the meaning of $\beta_0$ in this model?
     + By definition: $\beta_0 = \E(Y \mid x_1=0, x_2=0)$
     + but $x_1=0$ and $x_2=0$ is not possible. 
     + ...well not in the little dichotomous world of this example
  2. $x_1$ and $x_2$ are perfectly correlated 
     + each one is a linear function of the other, completely "collinear"
     + genderMale = 1 $-$ genderFemale
     + This strongly violates the regression assumptions
    
Conclusion: we need only one indicator variable    
for a categorical predictor variable with two categories
    
<!--
For matrix algebra aficionados, $X^TX$ has no unique inverse   
(since two columns in $X$ are linearly dependent)   

Thus we can't estimate the vector of $\beta$'s: $\;\;\widehat{\bbeta}=(\bX^T\bX)^{-1}\bX^T\bY$.
-->


#### What if there are more than two categories?

If there are three categories or more,    
we likely *cannot* just plug in values (like 0, 1, 2, ...) 

For example, marital status: single, married, widowed, divorced

If we assign values 1, 2, 3, 4, we assume these are ordered numeric categories.    
What is the correct ordering? Is it meaningful?

...and for the ordinal variable "preference" (very low, low, neutral, high, very high),   
if we assign values 1, 2, 3, 4, 5, we are stating that    
the average change in the response variable is the same from "very low" to "low"   
as it is from "high" to "very high" (a linear relationship)

...but maybe that's not true.


##### Indicator variables for predictors with more than two categories

A categorical predictor with $k$ possible values ($k$ feature types, groups, etc)    
requires a set of $k-1$ indicator variables.

The $k-1$ variables answer the sequence of questions:   
``Is feature $1$ present? Is feature $2$ present? ... Is feature $k-1$ present?"  

**Note:** 
If all answers are "no" then it must be true that feature $k$ is present.   
Likewise, if the answer to one of the $k-1$ questions is "yes", then the $k$-th feature is *not* present.

There can be at most one "yes" answer among the $k-1$ questions.

#### A little example with three (or five) categories

Consider the variable "smoking status" 

We can categorize it as _never smoker_, _occasional smoker_, or _heavy smoker_ 

$k = 3$.

If you want to be more specific: _never_, _ex-_, _light_, _moderate_, or _heavy smoker_

$k = 5$

**Note:** 
The different categories should be mutually exclusive.

When $k=3$, we can code this variable using $k-1 = 3-1 = 2$ indicator (dummy) variables.

\[ 
\mbox{occasSmoker} = \left\{ \begin{array}{l}
	    1 & \mbox{if occasionally smoked}\\ 
	    0 & \mbox{otherwise} 
	    \end{array} \right. 
\]
\[ 
\mbox{heavySmoker} = \left\{ \begin{array}{l}
	    1 & \mbox{if  smoked above some threshold frequency} \\
	    0 & \mbox{otherwise} 
	    \end{array} \right. 
\]

The omitted category, we might call neverSmoker  (corresponding to 0's for the other two indicators).   
This is called the  **base, control, or reference category**   

If the variable is ordinal (as it is here),   
we typically set the reference category to the "lowest" group    
and bring the other variables into the model in order from "lowest" to "highest".

Why? This usually makes the model coefficients easiest to interpret.

### Data Description

#### Re-analysis of Section 5.2 salary data

Survey of computer professionals at a large company

Response variable:   
$S =$ salary (thousands of dollars)

Predictor variables:   
$x =$ experience (years)   
$e =$ education (highest level: 1=HS, 2=BS, 3=higher)   
$m =$ management (management responsibility: 1=yes, 0=no)

```{r eval=FALSE}
salaryData <- read.delim("http://statistics.uchicago.edu/~collins/data/RABE5/P130.txt")
```
```{r eval=TRUE}
salaryData <- read.delim("./data/P130.txt")
n <- nrow(salaryData)

```

There are observations on n = `r n` computer professionals.

```{r}
head(salaryData, 10)
```


##### How to represent education in the model?

Three categories: HS, BS, and higher

In the textbook dataset, coded as ordinal (ordered categories: 1, 2, 3)

  + Should we treat education as ordinal?
    + The categories do have quantitative meaning (years of education)
    + But coding as numbers imposes a linearity constraint (perhaps not plausible)
  + Does "average increase corresponding to one unit change in education" make sense?
  + Does it make sense to expect the same average increase?
    + from HS to BS and again same salary change from BS to higher?
    + Perhaps diminishing marginal returns on salary?  (1, 3, 3.5) vs. (1, 2, 3)?
    
For now, let's treat education as a nominal variable   
and later see if we can justify a linear effect.

##### Generating an indicator variable

We need to generate 0-1 indicator variables for the education levels.

The following code will create three indicator variables     
even though we know we really need to only use two in the model.

3 categories $\leadsto$ 2 indicator variables

There are probably dozens of ways to do this in R.   
I Googled and found a package called "dummies".  That sounded worth a try!

I asked for dummy variables to be created based on the levels of the variable `E`

<br>
**SHOW CODE**
<br>

The new dataset looks like this:

```{r}
# install package once if not already installed
# install.packages("dummies")

# load the package when you first need it
library(dummies)

# Create the dummy variables for variable E (1, 2, 3)
salaryDummy <- dummy.data.frame(salaryData, names=c("E"))

# view the first few data observations
head(salaryDummy, 10)
# view the last few data observations
tail(salaryDummy, 10)
```

Hmmm....  I would have preferred to keep the original variable `E` as well.   
I'll just grab `E` from the original data and stick it into the new dataset.

<br>
**SHOW CODE**
<br>

```{r}
# Put the education variable back in the dataset
# Select the variables in the order you want them to appear in the dataset
salaryDummy <- salaryDummy %>%
  mutate(E = salaryData$E) %>%
  select(S, X, E, E1, E2, E3, M)
head(salaryDummy,10)
```

Here is a summary (counts) just to confirm that everything is as expected

```{r}
data.frame(tally(~ E, data=salaryDummy))

data.frame(tally(~ E1, data=salaryDummy))
data.frame(tally(~ E2, data=salaryDummy))
data.frame(tally(~ E3, data=salaryDummy))

# data.frame(tally(E1 + E2 + E3 ~ E, data=salaryDummy))
```

##### Fitting a first model including indicator variables

3 categories $\leadsto$ 2 indicator variables

I'll choose to use `E2` and `E3`  
Then, `E1` (high school) becomes the baseline, reference group

**Note:** 
If the categories do have a sense of order,   
setting the lowest as the reference category usually makes model easier to interpret.

Then, include the remaining variables from the next lowest up to the highest.

The textbook chose to use the highest level of education as the reference group.   
For myself, I found it very difficult to interpret the model coefficients "backwards".   
See textbook Table 5.3.

So, the model we would like to fit is then

\[
S  = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 m +  \epsilon
\]


#### Interpreting coefficients for indicator variables


The model above predicts the following: 

For people with HS only (reference category: $e_2=e_3=0$)
\[
S  = \beta_0 + \beta_1 x   + \beta_4 m +  \epsilon 
\]

What does $\beta_0$ represent?    

Do you think $\beta_0$ is positive or negative?
<br><br>

$\beta_0$ is the average salary for those with a HS education only   
with no experience ($x=0$) and not in a management position ($m=0$)

<br><br>

For people with a college degree ($e_2 = 1$) 

\[
S  = \beta_0 + \beta_1 x + \beta_2 + \beta_4 m +  \epsilon
\;=\; = (\beta_0 + \beta_2) + \beta_1 x + \beta_4 m +  \epsilon
\]

$\beta_2$ interpretation:   

<br><br>


Measures the difference in average salary for those with a college degree,    
relative to those with a high-school diploma only   
...adjusted for years of experience and management status.

Do you think $\beta_2$ is positive or negative?

What does the sum ($\beta_0 + \beta_2$) represent in the model? 


For people with a higher degree  ($e_3 = 1$) 

\[
S  = \beta_0 + \beta_1 x +  \beta_3  + \beta_4 m +  \epsilon
 \;=\; (\beta_0 + \beta_3) + \beta_1 x + \beta_4 m +  \epsilon
\]


What does $\beta_3$ represent in the model?     
Do you think $\beta_3$ is positive or negative?

<br>

What does $(\beta_0 + \beta_3)$ represent in the model? 

<br>

What does $\beta_1$ represent in the model?     
Do you think $\beta_1$ is positive or negative?

<br>

What does $\beta_4$ represent in the model? 
Do you think $\beta_4$ is positive or negative?

##### The estimated model coefficients

$$\yhat = \b0 + \b1 x + \b2 e_2 + \b3 e_3 + \b4 m$$

`lmfit.nominal <- lm(S ~ X + E2 + E3 + M, data=salaryDummy)`   

```{r}
lmfit.nominal <- lm(S ~ X + E2 + E3 + M, data = salaryDummy)
lmfit.null.model <- lm(S ~ 1, data = salaryDummy) # model with no predictors
tidy(lmfit.nominal) # coefficients and their statistics
anova(lmfit.null.model, lmfit.nominal) # F-test for all predictor coeff = 0
glance(lmfit.nominal)[-c(7:10)] # R^2 and other summaries
```

### Inference

#### F-tests to assess questions of interest

##### Does education effect salary?

$H_0: \beta_2 = \beta_3 = 0$

Full model: $S  = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 m +  \epsilon$

Reduced model: $S  = \beta_0 + \beta_1 x + \beta_4 m +  \epsilon$

Sample size: $n = `r n`$

```{r}
p.FM <- 4
p.RM <- 2
```

$$F = \frac{(\SSE(RM) - \SSE(FM)) \;/\; `r p.FM-p.RM`}{\SSE(FM) \;/\; `r n-p.FM-1`}$$

```{r}
lmfit.FM <- lm(S ~ X + E2 + E3 + M, data = salaryDummy) # full model estimate
lmfit.RM <- lm(S ~ X + M, data = salaryDummy) # reduced model estimate
anova(lmfit.RM, lmfit.FM) # F-test
```

##### Is the higher education really worth more than the Bachelors?

$H_0: \beta_2 = \beta_3$

Full model: $S  = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 m +  \epsilon$

Reduced model: $S  = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_2 e_3 + \beta_4 m +  \epsilon$

That is, $S  = \beta_0 + \beta_1 x + \beta_2 (e_2 + e_3) + \beta_4 m +  \epsilon$

You can fit this reduced model in R as follows:   
`lmfit.RM <- lm(S ~ X + I(E2 + E3) + M, data = salaryDummy)`

```{r}
p.FM <- 4
p.RM <- 3
```

$$F = \frac{(\SSE(RM) - \SSE(FM)) \;/\; `r p.FM-p.RM`}{\SSE(FM) \;/\; `r n-p.FM-1`}$$

```{r}
lmfit.FM <- lm(S ~ X + E2 + E3 + M, data = salaryDummy) # full model estimate
lmfit.RM <- lm(S ~ X + I(E2 + E3) + M, data = salaryDummy) # reduced model estimate
anova(lmfit.RM, lmfit.FM) # F-test
```

Hmmm...  Perhaps the higher education is not worth it in this industry!

##### What if we chose a different reference group?

$$S  = \beta_0 + \beta_1 x + \beta_2 e_1 + \beta_3 e_2 + \beta_4 m +  \epsilon$$

This is what the authors' chose in Section 5.2

The reference category has changed to the highest education group.

```{r}
lmfit2.nominal <- lm(S ~ X + E1 + E2 + M, data = salaryDummy)
tidy(lmfit2.nominal)
anova(lmfit.null.model, lmfit2.nominal)
glance(lmfit2.nominal)[-c(7:10)]
```

Things to notice...

  + The p-value for the F-test of $H_0: \beta_2=\beta_3$ for our earlier model    is identical to the p-value for the t-test of $H_0: \beta_3 = 0$ in the new model.  Why?

  + ANOVA table output is identical (we haven't really changed the overall model fit)
  
##### The "saturated model" (too many indicators)

What if we tried to use all three indicator variables in the model?

$$S  = \beta_0 + \beta_1 x + \beta_2 e_1 + \beta_3 e_2 + \beta_4 e_3 + \beta_5 m +  \epsilon$$

Well...  The `lm` function in R seems to be smart enough to ignore our overzealous attempt.

`lmfit3.nominal <- lm(S ~ X + E1 + E2 + E3 + M, data = salaryDummy)`

```{r}
lmfit3.nominal <- lm(S ~ X + E1 + E2 + E3 + M, data = salaryDummy)
tidy(lmfit3.nominal)
```

R took in the first two indicators and dropped the third (redundant).   
*That is so polite.  I wish R would fix my errors all the time.*

The effect is that the highest education group became the reference category.

I prefer the lowest group as the reference and would force R to do that myself:     
`lmfit.nominal <- lm(S ~ X + E2 + E3 + M, data = salaryDummy)`

<br><br>

There are other ways to set the base/control category in R.    
I chose to use the `dummies` package for transparency (pedagogy, simplicity).

#### Another salary analysis: ordinal variable

What if we had used the original education variable $e$ (coded 1, 2, 3)?

Then, the regression model would be

$$S  = \beta_0 + \beta_1 x + \beta_2 e + \beta_3 m +  \epsilon$$
and specifies that

 For people with HS only ($e=1$)
\[
S  = \beta_0 + \beta_1 x  + \beta_2 + \beta_3 m +  \epsilon
 \;=\; (\beta_0 + \beta_2) + \beta_1 x  + \beta_3 m +  \epsilon
\]

 For people with a BS ($e=2$)

\[
S  = \beta_0 + \beta_1 x + 2\beta_2 + \beta_3 m +  \epsilon
 \;=\; (\beta_0 + 2\beta_2) + \beta_1 x + \beta_3 m +  \epsilon
\]

 For people with higher degree ($e=3$)

\[
S  = \beta_0 + \beta_1 x +  3\beta_2  + \beta_3 m +  \epsilon
 \;=\; (\beta_0 + 3\beta_2) + \beta_1 x + \beta_3 m +  \epsilon
\]

##### Model fit with ordinal education variable

```{r}
lmfit.ordinal <- lm(S ~ X + E + M, data = salaryData)
tidy(lmfit.ordinal)
anova(lmfit.null.model, lmfit.ordinal)
glance(lmfit.ordinal)[-c(7:10)]
beta <- tidy(lmfit.ordinal)$estimate
```

The estimated coefficient for education is $\widehat{\beta}_2 = `r beta[3]`$. 

In particular, this model implies we expect    
the average salary difference between HS vs BS holders ($`r beta[3]`$) to be the same as    
the difference between BS vs higher-degree holders ($`r beta[3]`$).    

Does that seem reasonable?



#### Deciding between ordinal and nominal

How would we check if the model with ordinal education levels makes sense?

  + First, the variable has to make sense to be treated as ordered categories. 
    + For education level, we would expect some sort of monotone increasing effect,
    + but may be non-linear (diminishing marginal returns, not equal increments)
  
  + We could do a test by fitting the nominal variable model (indicator variables) 
    + Then test $H_0:  2\beta_2 = \beta_3$ to see if equal (linear) increments are appropriate
    + Does higher educ have twice the effect of BS relative to HS?
    + This was clearly not the case in the model with indicator variables for education level.
      + There is a large and statistically significant salary bump for HS-to-BS vs. BS-to-higher
      + ... the latter bump not even practically (or statistically) significant.

<br>

Of course, look at residual plots for both models: nominal and ordinal
  
##### An advantage of the ordinal representation

If an ordinal representation is appropriate for the model,   
we prefer to use the ordinal vs. nominal (indicator) representation.

What are the df for the two variance estimates: MSE = $\widehat{\sigma}$?    
Equivalently, what are the degrees of freedom for the two overall F-tests?   

Ordinal:

Nominal:

This "savings" in df is more efficient (higher statistical power per $n$ observations)

For the salary/education data, the difference is only one degree of freedom   
(since $k=3$ leads to $k-1=2$ indicator variables vs. one ordinal variable).

But, if the number of categories ($k$) is large and the sample size small,   
this difference becomes very important.



#### Investigating the residuals

Now that we have decided the indicator variables are most appropriate for 
bringing education level into the model, let's check the model assumptions.

```{r} 
lmfit.nominal <- lm(S ~ X + E2 + E3 + M, data = salaryDummy)
gf_point(rstandard(lmfit.nominal) ~ fitted(lmfit.nominal), data=salaryDummy) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal education levels)") %>%
  gf_hline(yintercept = c(-2, 0, 2), linetype = 2)
```

Whoa!  Why do we see clusters of points?

Let's highlight education level and the management indicator in the plot.

```{r}
gf_point(rstandard(lmfit.nominal) ~ fitted(lmfit.nominal), size = ~E, color = ~ M, data=salaryDummy) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal education levels)") %>%
  gf_hline(yintercept = c(-2, 0, 2), linetype = 2)
```
Wow!  Using the model

\[
S  = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 m +  \epsilon
\]

We are clearly not picking up all of the structure present in the data.

Here is another plot I think tells the story of the residuals a little better.

```{r}
gf_point(rstandard(lmfit.nominal) ~ (E + 3*M), size = ~E, color = ~ M, data=salaryDummy) %>%
  gf_labs(y = "standardized residuals", x = "Education and management categories") %>%
  gf_hline(yintercept = c(-2, 0, 2), linetype = 2)
```

### Interaction

#### Interactions ("effect modification")

All our models thus far specify that any given level/value of one predictor,    
the relative increment in (mean of) $Y$ due to another predictor is the same. 

There are many situations that the effects of one predictor on the response are    
NOT the same within different categories of some other predictor. 

An example:   
Response: risk of blood clots in women   
Predictor: number of months taking oral contraceptives (OC)

For women who don't smoke, the increase in risk per month on OC is modest.   
For women who smoke, the increase in risk per month on OC is very large.

That is, the relationship of OC and blood clot risk is different for smokers and non-smokers.

So, the following model would **not** be adequate:
$${\rm risk} = \beta_0 + \beta_1 {\rm smoke} + \beta_2 {\rm OC} + \epsilon$$

because for smokers (smoke = 1),
$${\rm risk} = (\beta_0 + \beta_1) + \beta_2 {\rm OC} + \epsilon$$
and for non-smokers (smoke = 0),
$${\rm risk} = \beta_0 + \beta_2 {\rm OC} + \epsilon$$
This model sets the additional risk-per-month = $\beta_2$ regardless of smoking status

In fact, if we plotted separate regression lines for clot risk versus time-on-OC    
for data from smokers and data from non-smokers,   
we would see two lines with **different slopes** for smokers and non-smokers.

The model above is inadequate.  It only allows for different intercepts, not different slopes.

**Interaction:** In this situation, we say that OC and smoking **interact**

The effect of smoking is a multiplicative (slope) effect, not just additive (intercept).

##### Including effect modification (interaction) in the model

We want a model that allows a different slope (steeper increase in risk from OC)   
for smokers vs. non-smokers

We include an "_interaction term_" between the primary predictor and the 
other predictor that modifies the effect of the primary predictor.

This is achieved by multiplying the two predictors together to form
a new predictor called an interaction or interaction term in the model.

$${\rm risk} = \beta_0 + \beta_1 {\rm smoke} + \beta_2 {\rm OC} + \beta_3 ({\rm OC}\times {\rm smoke}) + \epsilon$$

For smokers (smoke = 1),
$${\rm risk} = (\beta_0 + \beta_1) + (\beta_2 + \beta_3) {\rm OC} + \epsilon$$
and for non-smokers (smoke = 0),
$${\rm risk} = \beta_0 + \beta_2 {\rm OC} + \epsilon$$

In this scenario, $\beta_3 > 0$ and increases the **rate** at which blood clot risk increases  
for each month of oral contraceptive use for those who smoke vs. non-smokers.

##### Another interaction between quantitative and nominal variables

Is the effect of experience on salary the same for people with different education levels?

First, let's look at the fit of salary regressed on experience only:
$$S = \beta_0 + \beta_1 e_2 + \beta2 e_3 + \beta_4 x + \epsilon$$

```{r}
gf_point(S ~ X, data=salaryDummy, size = ~E, color = ~E) %>%
  gf_labs(x = "Experience (years)", y = "Salary ($1,000)")
```

Is the slope the same for each education level?

It appears that the slope of a regression line for each education level  
would have about the same slope as the overall fit seen here.

To explore whether there might by different effects (slopes) for experience   
according to education level, fit a separate regression line for each education level.

<br>

This is called a **stratified analysis**.

<br>

Look for non-parallel regression lines.

```{r}
lmfitE1 <- lm(S ~ X, data = subset(salaryDummy, E1 == 1))
lmfitE2 <- lm(S ~ X, data = subset(salaryDummy, E2 == 1))
lmfitE3 <- lm(S ~ X, data = subset(salaryDummy, E3 == 1))
gf_point(S ~ X, data=salaryDummy, size = ~E, color = ~E, alpha=0.6) %>%
  gf_labs(x = "Experience (years)", y = "Salary ($1,000)") %>%
  gf_coefline(model = lmfitE1) %>%
  gf_coefline(model = lmfitE2, linetype=2) %>%
  gf_coefline(model = lmfitE3, linetype=3)
```

The slopes do not appear to be the same!    

This suggests a differential effect of experience modified by education level:   
called a **modified effects** ...or **interaction effect**.

##### Incorporating interaction effects into the model

How "non-parallel" do the lines need to be to declare the slopes different?

To some extent, an answer requires considerations beyond the statistical.

But, we can formally test for the necessity of interaction effects in the model.

The new model looks like this:

\[
S = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 (e_2\times x) +
  \beta_5 (e_3 \times x) + \epsilon
\]

The product (multiplication) of experience and education variables are predictors in the model.

 For people with HS only ($e_2 = 0$, $e_3 = 0$) 
\[
S  = \beta_0 + \beta_1 x  +  \epsilon
\]

 For people with a BS ($e_2 = 1$, $e_3 = 0$)

\[
S  = (\beta_0 + \beta_2) + (\beta_1  + \beta_4) x +  \epsilon
\]

 For people with higher degree ($e_2 = 0$, $e_3 = 1$)

\[
S  = (\beta_0 + \beta_3) +  (\beta_1 + \beta_5) x +  \epsilon
\]

##### What is the effect of experience on salary in the model?

With one more year of experience, how much do we expect average salary to change?

Now it depends... on the level of education!

  + For HS, the effect (slope) is $\beta_1$   
  + For BS, it is ($\beta_1+\beta_4$)
  + For higher degrees, it is ($\beta_1+\beta_5$)

#### Fitting a model with interaction effects

We can create the additional predictors needed   
...or just ask R to include interaction effects.

I'll demonstrate both methods.

Once we have the model fit, we can use an F-test    
to evaluate the need for these extra predictors in the model   
(that is, to test whether the slopes are different)

Method #1: Just ask R to include interaction terms

`lmfit.interact <- lm(S ~ X + E2 + E3 + E2*X + E3*X, data = salaryDummy)`

```{r}
lmfit.interact <- lm(S ~ X + E2 + E3 + E2*X + E3*X, data = salaryDummy)
tidy(lmfit.interact)
```

Method #2: Create new predictors by multiplying old predictors together

`salaryInteract <- mutate(salaryDummy, E2X = E2 * X, E3X = E3 * X)`   
`lmfit.interact2 <- lm(S ~ X + E2 + E3 + E2X + E3X, data = salaryInteract)`

```{r}
salaryInteract <- mutate(salaryDummy, E2X = E2 * X, E3X = E3 * X)
lmfit.interact2 <- lm(S ~ X + E2 + E3 + E2X + E3X, data = salaryInteract)
tidy(lmfit.interact2)
```

<!--
**NOTE:** The order of the coefficients in the two tables above is different    
because R reports the "main effects" first, then the "interaction effects"
-->

##### F-test for interaction effects

From the regression output, the two interaction terms have low p-values,   
but not so low that we would reject $H_0: \beta = 0$ in either case.

Since we are testing two coefficients simultaneously, use an F-test or Bonferroni correction.

Here is the F-test:

Full model: $S = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 (e_2\times x) + \beta_5 (e_3 \times x) + \epsilon$

Reduced model: $S = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \epsilon$

The models differ by $2$ df (two coefficients).   
The full model has $n - 5 - 1 = `r n - 5 - 1`$ df.

```{r}
lmfit.FM <- lm(S ~ X + E2 + E3 + E2*X + E3*X, data = salaryDummy) # full model estimate
lmfit.RM <- lm(S ~ X + E2 + E3, data = salaryDummy) # reduced model estimate
anova(lmfit.RM, lmfit.FM) # F-test
```

This result suggests there is weak evidence at best of different slopes per education level.    
We might choose to omit the interaction terms from the model,    
opting for the simpler **main effects model**.

Note: The Bonferroni method is more conservative (less likely to reject null hypotheses),  
but at least when we do reject, we know exactly which terms were rejected.

If we reject an omnibus test like the F-test, we just know that one of the 
predictors has a coefficient significantly non-zero ...but not which predictor.
  
##### Interactions between continuous and ordinal variables

If we had used education as the original variable "$e$" (coded as 1,2,3)    
instead of indicator variables $e_2$ and $e_3$, then the regression (with interaction) would look like:

\[
S  = \beta_0 + \beta_1 x + \beta_2 e  + \beta_3 (e\times x) + \epsilon
\]

**Interpretation:**  
For each additional year of experience increase, the salary increase will depend on education.

  + For HS, the coefficient for experience is ($\beta_1+\beta_3$)
  + For BS, it is ($\beta_1+2\beta_3$)
  + For higher degrees, it is ($\beta_1+ 3\beta_3$)

From earlier analyses, we don't actually believe education is ordinal,  
so we won't bother to fit this model.

**Note:** Two continuous covariates that interact are interpreted similarly.

#### Summary of quantitative-categorical interaction

For a model with continuous predictor $x$    
and categorical predictor $c$ ($k=2$ levels: 0 and 1),    
the full intercation model is

\[ Y  = \beta_0 + \beta_1 x + \beta_2 c  + \beta_3 (c \times x) + \epsilon \]

The parameters ($\beta$s) in the model are:

  + $\beta_0$:  mean of $Y$ when $x=0, c=0$
  + $\beta_1$:  effect on mean of $Y$ of incrementing $x$ one unit, (when $c=0$)
  + $\beta_2$:  shift of mean of $Y$ when $c=1$, (when $x = 0$)
  + $\beta_3$:  When $c=1$ and when there is one unit increase in $x$, the
expected change in $Y$ is ($\beta_1+\beta_3$). 
    + So $\beta_3$ is the **additional**
effect on $Y$ of a unit increase in $x$ when $c=1$, comparing when $c=0$.

##### The variety of models with and without interaction

 Different intercepts, different slopes
\[ Y  = \beta_0 + \beta_1 x + \beta_2 c  + \beta_3 (c \times x) + \epsilon \]

 Different intercepts, same slope
\[ Y  = \beta_0 + \beta_1 x + \beta_2 c  + \epsilon \]

 Same intercept, different slopes
\[ Y  = \beta_0 + \beta_1 x + \beta_3 (c \times x) + \epsilon \]

**The last model is not common.**

Instead, it is common practice when including interaction terms to also include all main effects.





##### Comments on regression with interactions

  +  When interaction effects exist, we call the effects of predictor alone **main effects**

Accepted practice:    
If interaction effects are in the model, leave the main effects in the model too    
...even if not statistically significant (makes interpretation much easier)

  + In the presence of interaction effects, 
    + we can no longer talk about effects of one predictor variable without considering the value taken on by another.
    + That is, the phrase, "while other variables are held constant" makes no sense

  + A critical issue with interaction effects is statistical power. 
    + The interaction effects may be present, but detecting them depends on adequate sample size for the many possible predictor-value-multiplied-by-other-predictor-value combinations

Some other thoughts you can read later:   

There are some situations in which you may want to leave one or all of the main effects out. It must be that the interaction effect is more relevant in predicting the response variable than the main. Often, sample size is really small and so a parsimonious model is desired. It could be that main effect itself is intuitively not relevant for predicting the response variable but the interaction is. OR when including the main effect would result in violations of assumptions while the interaction terms would not, e.g. the main effects and the interaction terms are highly correlated and including both would result in collinearity, and you may drop one depending on which is more relevant or more significant.

#### Using residual plots to help choose an appropriate model

Residuals from the model with nominal education level ($e_2 = 0, 1$ and $e_3 = 0, 1$)
\[
S  = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 m +  \epsilon
\]

```{r}
gf_point(rstandard(lmfit.nominal) ~ fitted(lmfit.nominal)) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal education levels)") %>%
  gf_hline(yintercept = 0, linetype = 2)
gf_point(rstandard(lmfit.nominal) ~ fitted(lmfit.nominal), size = ~E, color = ~ M, data=salaryDummy) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal education levels)") %>%
  gf_hline(yintercept = 0, linetype = 2)
```

Residuals from the model with ordinal education level ($e = 1, 2, 3$)
\[
S  = \beta_0 + \beta_1 x + \beta_2 e + \beta_3 m +  \epsilon
\]

```{r}
gf_point(rstandard(lmfit.ordinal) ~ fitted(lmfit.ordinal)) %>%
  gf_labs(y = "standardized residuals", x = "yhat (ordinal education levels)")
gf_point(rstandard(lmfit.ordinal) ~ fitted(lmfit.ordinal), size = ~E, color = ~ M, data=salaryDummy) %>%
  gf_labs(y = "standardized residuals", x = "yhat (ordinal education levels)")
```

Residuals from the model with ordinal education level ($e_2, e_2$) and experience-education interaction
\[
S = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 (e_2\times x) + \beta_5 (e_3 \times x) + \beta_6 m + \epsilon
\]

```{r}
gf_point(rstandard(lmfit.interact) ~ fitted(lmfit.interact)) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal educ, experience interaction)")
gf_point(rstandard(lmfit.interact) ~ fitted(lmfit.interact), size = ~E, color = ~ M, data=salaryDummy) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal educ, experience interaction)")
```

Remember that we did not consider the interaction effects to be significant,   
so the above plot is just for illustration purposes.

In all residual plots, it seems management status has a differential effect by education level.

Even though interaction between experience and education level was not a significant improvement,   
perhaps we need to include interaction of management status and education level?

First, does management also have a differential effect on experience?

```{r}
lmfitM0 <- lm(S ~ X, data = salaryDummy[salaryDummy$M==0, ])
lmfitM1 <- lm(S ~ X, data = salaryDummy[salaryDummy$M==1, ])
gf_text(S ~ X, data=salaryDummy, label = ~E) %>%
  gf_labs(x = "Experience (years)", y = "Salary ($1,000)") %>%
  gf_coefline(model = lmfitM0) %>%
  gf_coefline(model = lmfitM1)
```

The regression lines are pretty much parallel.   
So, we won't consider an experience-management interaction effect further.

Now, what about education-management interaction?

We can fit a separate regression line for each of 6 education-management combinations.

**Caution:** We are really slicing up this small data set into little bits: $n = `r n`$.

```{r}
lmfitE1M0 <- lm(S ~ X, data = salaryDummy[(salaryDummy$M==0 & salaryDummy$E==1), ])
lmfitE2M0 <- lm(S ~ X, data = salaryDummy[(salaryDummy$M==0 & salaryDummy$E==2), ])
lmfitE3M0 <- lm(S ~ X, data = salaryDummy[(salaryDummy$M==0 & salaryDummy$E==3), ])
lmfitE1M1 <- lm(S ~ X, data = salaryDummy[(salaryDummy$M==1 & salaryDummy$E==1), ])
lmfitE2M1 <- lm(S ~ X, data = salaryDummy[(salaryDummy$M==1 & salaryDummy$E==2), ])
lmfitE3M1 <- lm(S ~ X, data = salaryDummy[(salaryDummy$M==1 & salaryDummy$E==3), ])
gf_text(S ~ X, data=salaryDummy, label = ~E, color = ~M) %>%
  gf_labs(x = "Experience (years)", y = "Salary ($1,000)") %>%
  gf_coefline(model = lmfitE1M0) %>%
  gf_coefline(model = lmfitE2M0) %>%
  gf_coefline(model = lmfitE3M0) %>%
  gf_coefline(model = lmfitE1M1, linetype=2) %>%
  gf_coefline(model = lmfitE2M1, linetype=2) %>%
  gf_coefline(model = lmfitE3M1, linetype=2)
```

These lines look very close to parallel. They are not *perfectly* parallel, but very close. This suggests that we try fitting a single model where the 6 different management-education subgroups share the same slope, but are allowed to have different intercepts.


So, let's fit the following model:
\[
S = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 (e_2\times m) + \beta_5 (e_3 \times m) + \beta_6 m + \epsilon
\]

Each of the 6 subgroups will have the same $\beta_1$, but they will have six different intercepts.



`lmfit.interact.educ.manage <- lm(S ~ X + E2 + E3 + E2*M + E3*M + M, data = salaryDummy)`

```{r}
lmfit.interact.educ.manage <- lm(S ~ X + E2 + E3 + E2*M + E3*M + M, data = salaryDummy)
tidy(lmfit.interact.educ.manage)
```

The education-management interaction effects are highly significant.

What do the residuals from this model look like?

```{r}
gf_point(rstandard(lmfit.interact.educ.manage) ~ fitted(lmfit.interact.educ.manage)) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal educ, management interaction)")
gf_point(rstandard(lmfit.interact.educ.manage) ~ fitted(lmfit.interact.educ.manage), size = ~E, color = ~ M, data=salaryDummy) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal educ, management interaction)")
```

Hmmmm....  It seems there is one manager with a college education   
who gets paid much, much, much lower than the model would predict.

In order to see the pattern in the residuals better, I'm going to temporarily remove this observation.

```{r}
omit <- which(rstandard(lmfit.interact.educ.manage) < -5)
omit
lmfit.interact.educ.manage.omit <- lm(S ~ X + E2 + E3 + E2*M + E3*M + M, data = salaryDummy[-omit,])
tidy(lmfit.interact.educ.manage.omit)
gf_point(rstandard(lmfit.interact.educ.manage.omit) ~ fitted(lmfit.interact.educ.manage.omit)) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal educ, management interaction)")
gf_point(rstandard(lmfit.interact.educ.manage.omit) ~ fitted(lmfit.interact.educ.manage.omit), size = ~E, color = ~ M, data=salaryDummy[-omit, ]) %>%
  gf_labs(y = "standardized residuals", x = "yhat (nominal educ, management interaction)")
```

What do you think about the residual plot now?   
Does it support the model assumptions?



Does the outlier have much influence on predictions?

```{r}
h.outlier <- hatvalues(lmfit.interact.educ.manage)[omit]
C.outlier <- cooks.distance(lmfit.interact.educ.manage)[omit]
C <- cooks.distance(lmfit.interact.educ.manage)
gf_point(cooks.distance(lmfit.interact.educ.manage) ~ rstandard(lmfit.interact.educ.manage)) %>%
  gf_labs(x = "standardized residuals", y = "Cook's distance (nominal educ, manage interact)")
```

Regression results with outlier included.   
$S = \beta_0 + \beta_1 x + \beta_2 e_2 + \beta_3 e_3 + \beta_4 (e_2\times m) + \beta_5 (e_3 \times m) + \beta_6 m + \epsilon$

```{r}
tidy(lmfit.interact.educ.manage)
glance(lmfit.interact.educ.manage)[-c(7:10)]
```

Regression results with outlier omitted.

```{r}
tidy(lmfit.interact.educ.manage.omit)
glance(lmfit.interact.educ.manage.omit)[-c(7:10)]
```

The outlier has very little influence on the regression results,   
...except a huge reduction in variance.

Plus, Cook's distance implies this observation may have influence on predictions.

##### Checking other model assumptions with residuals

Excluding the residual, we confirmed the linearity and non-constant variance assumptions.

Here are more residual plots (with the outlier omitted)

```{r}
gf_point(rstandard(lmfit.interact.educ.manage.omit) ~ X, data = salaryDummy[-omit, ]) %>%
  gf_labs(y = "standardized residuals", x = "x (years of experience)")

# Googled quite a bit to get the legends labeled nicely on this plot
gf_point(rstandard(lmfit.interact.educ.manage.omit) ~ (E + 3*M), size = ~ as.factor(M), color = ~ as.factor(E), data=salaryDummy[-omit, ]) %>%
  gf_labs(y = "standardized residuals", x = "Education and management categories") %>%
  gf_hline(yintercept = c(-2, 0, 2), linetype = 2) + 
  scale_size_discrete(range = c(1.5, 3), name="Manager", 
                      breaks=c("0", "1"),  labels=c("No", "Yes")) +
  scale_color_discrete(name="Education", 
                      breaks=c("1", "2", "3"),  labels=c("HS", "BS", "Grad"))
```

The last plot is interesting (and is an improvement on textbook Figure 5.5). 

There seems to be more variability in salary for non-managers vs. managers.   
This violates the assumption of constant variance for all levels of the predictors.

So, this model is quite good, but we might be overestimating salary variability for managers.


