# R for Psychological Research, Lesson 12: Correlation
# Code from the lesson page, in order. Run it line by line with Ctrl+Enter (Cmd+Enter on a Mac).
# Lines that start with # are comments: R ignores them.


# ---- Set up ----

library(tidyverse)
students <- read_csv("data/students.csv", show_col_types = FALSE)


# ---- Plot first ----

ggplot(students, aes(x = StudyHours, y = ExamScore)) +
  geom_point(alpha = 0.5) +
  geom_smooth(method = "lm")


# ---- Calculate and test ----

cor(students$StudyHours, students$ExamScore, use = "complete.obs")

cor.test(students$StudyHours, students$ExamScore)


# ---- Many at once ----

students %>%
  select(StudyHours, Attendance, Sleep, Stress, ExamScore) %>%
  cor(use = "pairwise.complete.obs") %>%
  round(2)


# ---- Spearman's rho ----

cor.test(students$Stress, students$Sleep, method = "spearman")
