Regression with Qualitative Variables
This lesson covers regression with a categorical (a.k.a., qualitative) independent variable.
Model script
#install.packages("tidyverse") # uncomment if tidyverse not installed
#install.packages("rio") # uncomment if rio not installed
#install.packages("fastDummies") # uncomment if fastDummies not installed
library(tidyverse)
library(rio)
library(fastDummies)
data <- import("https://learndata.net/nycschools.dta")
# basic data processing needed to use this dataset, copied from Part 3:
# convert quantitative variables currently
# stored as characters to numbers
data <- data |> mutate(thgrmathela = parse_number(thgrmathela))
# rename thgrmathela to something more descriptive
data <- data |> rename(combined_score = thgrmathela)
# for a string variable, it can be directly included
# in a regression as a categorical independent variable
summary(lm(combined_score ~ schooltype, data = data))
# if I want more control over how the categorical
# variable is handled in the regression, I can use
# the fastDummies package to create a set of dummy
# variables from my categorical variable, and then
# I can enter these variables directly into the
# regression (note: the variable schooltype_K-8 has
# a hyphen in it, which requires referring to it as
# `schooltype_K-8`)
data <- data |> dummy_cols("schooltype")
summary(lm(combined_score ~ schooltype_Elementary +
`schooltype_K-8` + schooltype_Middle, data = data))
# I can see how my results look different if I
# change the reference category by leaving out one
# category
summary(lm(combined_score ~ schooltype_Elementary +
schooltype_Middle, data = data))
# if a categorical variable is stored numerically, it
# will be (incorrectly) treated as a quantitative variable
# by default in a regression:
summary(lm(combined_score ~ district, data = data))
# we can enclose the variable name with factor() so
# R will know to treat the variable as categorical
summary(lm(combined_score ~ factor(district), data = data))Key concepts/syntax:
dummy_cols(): create a set of dummy (binary) variables from a categorical variable, using thefastDummiespackagedata <- data |> dummy_cols("schooltype")factor(): treat a variable as a factor (categorical variable)summary(lm(combined_score ~ factor(district), data = data))