Skip to main content

Section 7.6 Correlation Matrix

Right now, we only have three variables we want to run correlations with. But, what if we had 50? Are we going to run 50 lines of code? No! We can, instead, run a correlation matrix, which conducts a correlation between any and all numeric values. The key here is that your data must only contain numeric values, so make sure you clean your data first. Again, as before, we can utilize the cor command.

Hint:.

Use = "pairwise.complete.obs" handles any missing values safely
# Selecting numeric variables only (if dataset contains non-numeric columns)
library(tidyverse)

examData_numeric <- examData |> dplyr::select(where(is.numeric))

corr_matrix <- cor(examData_numeric, use = "pairwise.complete.obs")

corr_matrix
studying_hours exam_score anxiety_score
studying_hours      1.0000000  0.3900419    -0.7122237
exam_score          0.3900419  1.0000000    -0.4449023
anxiety_score      -0.7122237 -0.4449023     1.0000000
Boom! We were able to calculate the correlation coefficients in one line of code for all three variables. We are always aiming to get the most done with as little code as possible.