# ferdo R Lab | Lesson 4 v1.0 | Base R graphics
# All records synthetic. Run from the extracted student package 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"))

scored <- d$quiz_score[!is.na(d$quiz_score)]
ok <- complete.cases(d[,c("study_hours","quiz_score")])
means <- tapply(d$quiz_score,d$group,mean,na.rm=TRUE)
medians <- tapply(d$quiz_score,d$group,median,na.rm=TRUE)
group_sizes <- table(d$group)
histogram <- hist(scored,breaks=seq(40,100,by=10),
                  right=FALSE,plot=FALSE)
hist_counts <- as.integer(histogram$counts)

cat("Valid quiz scores:",length(scored),"\n")
cat("Complete hour-score pairs:",sum(ok),"\n")
print(group_sizes)
print(medians)
print(means)
print(hist_counts)

# Keep all four graphs together on one graphics page.
oldpar <- par(mfrow=c(2,2), mar=c(4.4,4.4,3.1,1))
hist(scored,breaks=seq(40,100,by=10),right=FALSE,
     main="Quiz scores (fictional)",xlab="Quiz score",
     ylab="Number of observations")
boxplot(quiz_score ~ group,data=d,
        main="Scores by group (fictional)",
        xlab="Group",ylab="Quiz score",ylim=c(0,100))
plot(d$study_hours[ok],d$quiz_score[ok],
     main="Hours & quiz score (fictional)",
     xlab="Study hours (hours)",ylab="Quiz score",pch=19)
barplot(means,ylim=c(0,100),main="Group mean quiz scores",
        xlab="Group",ylab="Mean quiz score")
par(oldpar)

# Different purpose: categorical frequency, NOT score histogram
# barplot(table(d$group),xlab="Group",ylab="Number of rows")
# TASK: Explain why the four panels use 11, 11, 10 and 11 scores.
