# R for Psychological Research, Lesson 6: Change data
# 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)


# ---- mutate(): add a column ----

students %>%
  mutate(Change = Wellbeing_T2 - Wellbeing_T1) %>%
  select(ID, Wellbeing_T1, Wellbeing_T2, Change) %>%
  head(3)

students <- students %>%
  mutate(Change = Wellbeing_T2 - Wellbeing_T1)


# ---- if_else(): two groups ----

students <- students %>%
  mutate(Age_Group = if_else(Age >= 21, "21 and over", "Under 21"))

students %>% count(Age_Group)


# ---- case_when(): recode ----

students <- students %>%
  mutate(LearningStyle = case_when(
    LearningStyle == 0 ~ "Visual",
    LearningStyle == 1 ~ "Kinaesthetic",
    LearningStyle == 2 ~ "Auditory",
    LearningStyle == 3 ~ "Reading/Writing"
  ))

students %>% count(LearningStyle)

students %>%
  mutate(Exam_Band = case_when(
    ExamScore >= 70 ~ "High",
    ExamScore >= 50 ~ "Middle",
    .default = "Low"
  )) %>%
  count(Exam_Band)


# ---- Missing values ----

sum(is.na(students$Sleep))
students %>% filter(is.na(Sleep)) %>% select(ID, Sleep)
students %>% drop_na(Sleep) %>% nrow()
