Categorical explanatory variables

Introduction to Regression in R

Richie Cotton

Data Evangelist at DataCamp

Fish dataset

  • Each row represents one fish.
  • There are 128 rows in the dataset.
  • There are 4 species of fish.
species mass_g
Bream 242.0
Perch 5.9
Pike 200.0
Roach 40.0
... ...
Introduction to Regression in R

Visualizing 1 numeric and 1 categorical variable

library(ggplot2)

ggplot(fish, aes(mass_g)) +
  geom_histogram(bins = 9) +
  facet_wrap(vars(species))

A faceted histogram of fish counts versus their weights. Each panel contains a species: bream, perch, pike, or roach.

Introduction to Regression in R

Summary statistics: mean mass by species

fish %>% 
  group_by(species) %>% 
  summarize(mean_mass_g = mean(mass_g))
# A tibble: 4 x 2
  species mean_mass_g
  <chr>         <dbl>
1 Bream          618.
2 Perch          382.
3 Pike           719.
4 Roach          152.
Introduction to Regression in R

Linear regression

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

Coefficients:
 (Intercept)  speciesPerch   speciesPike  speciesRoach  
       617.8        -235.6         100.9        -465.8 
Introduction to Regression in R

No intercept

lm(mass_g ~ species + 0, data = fish)
Call:
lm(formula = mass_g ~ species + 0, data = fish)

Coefficients:
speciesBream  speciesPerch   speciesPike  speciesRoach  
       617.8         382.2         718.7         152.0 
Introduction to Regression in R

Let's practice!

Introduction to Regression in R

Preparing Video For Download...