Associations (for Quantitative Variables)

Model script

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

# load in and prepare the data
nycschools <- import("https://learndata.net/nycschools.dta")
nycschools <- nycschools |> mutate(thgrmathela = parse_number(thgrmathela))
nycschools <- nycschools |> rename(combined_score = thgrmathela)

# calculate a correlation coefficient
cor(nycschools$overallscore, nycschools$combined_score, use = "complete")

# note that without the proper "use" option, we get
# "NA" as our result due to missing observations
cor(nycschools$overallscore, nycschools$combined_score)

# three different ways to make the same plot
plot(nycschools$combined_score, nycschools$overallscore)
plot(nycschools$overallscore ~ nycschools$combined_score)
plot(overallscore ~ combined_score, data = nycschools)

# add a regression line to the current plot
abline(lm(overallscore ~ combined_score, data = nycschools))

# create a binned scatter plot
binsreg(nycschools$combined_score, nycschools$overallscore)

Key concepts/syntax:

  1. cor(): calculate correlations among variables

    cor(nycschools$overallscore, nycschools$combined_score, use = "complete")
  2. plot(): create a simple 2D plot, such as a scatter plot

    plot(nycschools$combined_score, nycschools$overallscore)
  3. abline(lm()): add a regression line to the current plot

    abline(lm(overallscore ~ combined_score, data = nycschools))