One model with an interaction

Intermediate Regression in R

Richie Cotton

Data Evangelist at DataCamp

What is an interaction?

In the fish dataset

The effect of length on the expected mass is different for different species.

 

More generally

The effect of one explanatory variable on the expected response changes depending on the value of another explanatory variable.

Intermediate Regression in R

Specifying interactions

No interactions

response ~ explntry1 + explntry2

With interactions (implicit)

response_var ~ explntry1 * explntry2

With interactions (explicit)

response ~ explntry1 + explntry2 + explntry1:explntry2

No interactions

mass_g ~ length_cm + species

With interactions (implicit)

mass_g ~ length_cm * species

With interactions (explicit)

mass_g ~ length_cm + species + length_cm:species
Intermediate Regression in R

Running the model

lm(mass_g ~ length_cm * species, data = fish)
Call:
lm(formula = mass_g ~ length_cm * species, data = fish)

Coefficients:
           (Intercept)               length_cm            speciesPerch             speciesPike  
             -1035.348                  54.550                 416.172                -505.477  
          speciesRoach  length_cm:speciesPerch   length_cm:speciesPike  length_cm:speciesRoach  
               705.971                 -15.639                  -1.355                 -31.231
Intermediate Regression in R

Easier to understand coefficients

mdl_inter <- lm(mass_g ~ species + species:length_cm + 0, data = fish)
Call:
lm(formula = mass_g ~ species + species:length_cm + 0, data = fish)

Coefficients:
          speciesBream            speciesPerch             speciesPike            speciesRoach  
              -1035.35                 -619.18                -1540.82                 -329.38  
speciesBream:length_cm  speciesPerch:length_cm   speciesPike:length_cm  speciesRoach:length_cm  
                 54.55                   38.91                   53.19                   23.32 
Intermediate Regression in R

Familiar numbers

          speciesBream            speciesPerch             speciesPike            speciesRoach  
              -1035.35                 -619.18                -1540.82                 -329.38  
speciesBream:length_cm  speciesPerch:length_cm   speciesPike:length_cm  speciesRoach:length_cm  
                 54.55                   38.91                   53.19                   23.32 
coefficients(mdl_bream)
(Intercept)   length_cm 
-1035.34757    54.54998
Intermediate Regression in R

Let's practice!

Intermediate Regression in R

Preparing Video For Download...