Qualitative-Quantitative Relationships

This lesson covers relationships between categorical (a.k.a., qualitative) variables and quantitative variables.

Model script

#install.packages("tidyverse")  # uncomment if tidyverse not installed
#install.packages("rio")  # uncomment if rio not installed
#install.packages("psych")  # uncomment if psych not installed
library(tidyverse)
library(rio)
library(psych)

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)

# create a table with summary statistics for combined_score by schooltype  
describeBy(data$combined_score, group=data$schooltype)

# an alternative way to create a similar table using tidyverse functions
data |>
  group_by(schooltype) |> 
  summarize(
    n = sum(!is.na(combined_score)),
    mean = mean(combined_score, na.rm = TRUE),
    median = median(combined_score, na.rm = TRUE),
    sd = sd(combined_score, na.rm = TRUE)
  )

# create a set of box plots showing this same relationship
boxplot(combined_score ~ schooltype, data = data)

# let's use a different qualitative variable (overallgrade)
boxplot(combined_score ~ overallgrade, data = data)

# now recreate the prior boxplot filtering out blanks
# (missing values) before creating the plot
data_nonmissing_grade <- data |> filter(overallgrade != "")
boxplot(combined_score ~ overallgrade, data = data_nonmissing_grade)

Key concepts/syntax:

  1. describeBy(): compare means/medians across categories, using the psych package

    describeBy(data$combined_score, group=data$schooltype)
  2. group_by(): a tidyverse function to divide a dataset into groups (subsamples)1

    data |>
      group_by(schooltype) |> 
      summarize(
        mean = mean(combined_score, na.rm = TRUE),
      )
  3. summarize(): a tidyverse function to get summary statistics (descriptive statistics)2

    data |>
      group_by(schooltype) |> 
      summarize(
        mean = mean(combined_score, na.rm = TRUE),
      )
  4. ~: this symbol (a “tilde”) is used in R formula notation; it separates the dependent variable (which comes before ~) from the independent variable (which comes after ~)

    boxplot(combined_score ~ schooltype, data = data)

  1. For more explanation, see https://moderndive.com/v2/03-wrangling.html#sec-groupby or https://r4ds.hadley.nz/data-transform.html#group_by↩︎

  2. For more explanation, see https://moderndive.com/v2/03-wrangling.html#sec-summarize or https://r4ds.hadley.nz/data-transform.html#sec-summarize↩︎