# ferdo R Lab | Lesson 3 | Base R guided demo
# Synthetic data. Set working directory to the unpacked ZIP root.
stopifnot(file.exists("data/class_synthetic.csv"))
d <- read.csv("data/class_synthetic.csv",
              na.strings=c("","NA"), stringsAsFactors=FALSE)
d$group <- factor(d$group, levels=c("A","B"))

# 1. Safe filtering: NA comparisons must be handled.
valid_score <- !is.na(d$quiz_score)
high_flag <- valid_score & (d$quiz_score >= 70)
high <- d[high_flag, c("student_id","quiz_score","group"), drop=FALSE]
print(high)

# 2. Group size is not always the denominator of the mean.
group_size <- table(d$group)
group_prop <- prop.table(group_size)
valid_n <- tapply(valid_score, d$group, sum)
group_means <- tapply(d$quiz_score, d$group, mean, na.rm=TRUE)
score_summary <- aggregate(quiz_score ~ group, data=d, FUN=mean)
print(group_size)
print(group_prop)
print(valid_n)
print(group_means)
print(score_summary)

# 3. High-score share among OBSERVED scores, not among all rows.
high_count <- tapply(high_flag, d$group, sum)
high_share <- high_count / valid_n
print(high_share)

# 4. Two-variable complete cases change the available sample.
ok <- complete.cases(d[,c("study_hours","quiz_score")])
complete_data <- d[ok, ,drop=FALSE]
complete_means <- tapply(complete_data$quiz_score, complete_data$group, mean)
print(complete_means)
cat("Complete cases:",sum(ok),"\n")

# 5. A simple display of grouped means. Not a causal test.
barplot(group_means,ylim=c(0,100),
        xlab="Group",ylab="Mean quiz score",
        main="Synthetic group means")
# Student reflection: What does this plot NOT show?
