# Chapter 4 Descriptive Syntax in R.

class <- read.csv("c:\\temp\\classroom.csv", h = T)

########################
# Descriptive Summary #1
########################

# Level 1 Descriptive Statistics

attach(class)
level1 <- data.frame(sex,minority,mathkind,mathgain,ses)
summary(level1)

# Level 2 Descriptive Statistics

level2 <- aggregate(class,list(classid = class$classid),mean)
summary(level2$yearstea)
dim(level2)

# Level 3 Descriptive Statistics

level3 <- aggregate(class,list(schoolid = class$schoolid),mean)
summary(level3$housepov)
dim(level3)

########################
# Descriptive Summary #2
########################

class.nomiss <- subset(class, !is.na(mathknow))

# Level 1 Descriptive Statistics

level1 <- data.frame(class.nomiss$sex,class.nomiss$minority,class.nomiss$mathkind,class.nomiss$mathgain,class.nomiss$ses)
summary(level1)
dim(level1)

# Level 2 Descriptive Statistics

level2.agg <- aggregate(class.nomiss,list(classid = class.nomiss$classid),mean)
level2 <- data.frame(level2.agg$yearstea,level2.agg$mathknow,level2.agg$mathprep)
summary(level2)
dim(level2)

# Level 3 Descriptive Statistics

level3.agg <- aggregate(class.nomiss,list(schoolid = class.nomiss$schoolid),mean)
summary(level3.agg$housepov)
dim(level3.agg)

#########################
# Boxplots for Figure 4.2
#########################

class.first8 <- class[class$schoolid <= 8,]
par(mfrow=c(4,2))
for (i in 1:8) 
{boxplot(class.first8$mathgain[class.first8$schoolid==i] ~ class.first8$classid[class.first8$schoolid==i])}