# ferdo R Lab - Ders 2 (v1.0): CSV, types, indexing and missing values
# Synthetic observations ONLY; not real UCL student data.
# RStudio working directory should be the unpacked package root.
stopifnot(file.exists("data/class_synthetic.csv"))
class_data <- read.csv("data/class_synthetic.csv",
                       na.strings = c("", "NA"), stringsAsFactors = FALSE)
class_data$group <- factor(class_data$group, levels = c("A","B"))
cat("Rows / columns:\n")
print(dim(class_data))
str(class_data)
print(head(class_data, 3))

# Indexing by row, column name and logical condition
print(class_data[1, ])
print(class_data[1:3, c("student_id", "group")])
print(class_data$class_data)  # NULL: no column with that name
print(names(class_data))

# Explicit missing-value checks
print(colSums(is.na(class_data)))
print(mean(class_data$quiz_score))                   # NA
print(mean(class_data$quiz_score, na.rm = TRUE))     # 718/11
print(table(class_data$group))

# Safe indexing: exclude missing scores before comparing
high <- class_data[!is.na(class_data$quiz_score) &
                     class_data$quiz_score >= 70, ]
print(high[, c("student_id","quiz_score"), drop = FALSE])

# A graph needs BOTH variables present (10 complete pairs)
ok <- complete.cases(class_data[, c("study_hours","quiz_score")])
plot(class_data$study_hours[ok], class_data$quiz_score[ok],
     xlab = "Study hours", ylab = "Quiz score", pch = 19,
     main = "Synthetic data: association is not causation")
cat("Complete pairs used in plot:", sum(ok), "\n")

# STUDENT PROMPT: Why are there 11 valid quiz scores but only 10 points?
