4  Interaction

Linear regression where the effect of one variable depends on another.


I’ve recently begun restructuring the website. This chapter is under construction.

4.1 Summary

Mathematical formula:

\[\begin{align} \eta &= \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2 + \beta_3 \cdot x_1 \cdot x_2 \\ \tag{1}\label{interactionslope}\\ x_2 &= \begin{cases}1 \quad \text{if B}\\ 0 \quad \text{otherwise} \end{cases} \end{align}\]

Code:

model <- lm(y ~ x * group, data)
import statsmodels.formula.api as smf
model = smf.ols("y ~ x * group", data).fit()

To do.

To do.

To do.

Mathematical formula:

\[\begin{align} \eta &= \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2 + \beta_3 \cdot x_1 \cdot x_2 \\ \tag{2}\label{interactiondummy}\\ x_1 &= \begin{cases}1 \quad \text{if B}\\ 0 \quad \text{otherwise} \end{cases}, \quad x_2 = \begin{cases}1 \quad \text{if treated}\\ 0 \quad \text{otherwise} \end{cases} \end{align}\]

Code:

model <- lm(y ~ group * treatment, data)
import statsmodels.formula.api as smf
model = smf.ols("y ~ group * treatment", data).fit()

To do.

To do.

To do.

To do.

\[\begin{align} \eta &= \beta_0 + \beta_1 \cdot x_1 + \beta_2 \cdot x_2 + \beta_3 \cdot x_1 \cdot x_2 \tag{3}\label{interactionslopeslope} \end{align}\]

model <- lm(y ~ x1 * x2, data)
import statsmodels.formula.api as smf
model = smf.ols("y ~ x1 * x2", data).fit()

4.2 Quiz

To do.

To do.

To do.

To do.

To do.

To do.

To do.

To do.

Interactive app

Practice the concepts covered in this chapter:

Regression tables

This app runs in your browser. The first time, your browser downloads about 50 MB, which can take a minute or more.

4.3 Apply your knowledge

Now analyze a dataset yourself. Start with the worked examples, then do the exercise:

  1. Save the data and qmd file in the same location on your computer.
  2. Open the qmd file in RStudio.
  3. Set working directory to source file location.
    (Session > Set Working Directory > To Source File Location)
  4. R will now read from the folder the qmd file is located, so you can just use read.csv("name-of-data.csv").