# R for Psychological Research, Lesson 11: z-scores
# 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)


# ---- Calculate z-scores ----

students <- students %>%
  mutate(z_Exam = (ExamScore - mean(ExamScore)) / sd(ExamScore))

students %>% select(ID, ExamScore, z_Exam) %>% head(4)

students <- students %>%
  mutate(z_Stress = (Stress - mean(Stress)) / sd(Stress))

students %>% filter(ID == "S005") %>% select(ID, ExamScore, z_Exam, Stress, z_Stress)

students %>% filter(abs(z_Exam) > 2) %>% select(ID, ExamScore, z_Exam)


# ---- One-sample z-test ----

mu <- mean(students$Stress)
sigma <- sd(students$Stress)
mature <- students %>% filter(Age >= 25)
nrow(mature)

library(BSDA)
z.test(x = mature$Stress, mu = mu, sigma.x = sigma)
