# Aggregate Example # Create bar plots with data processed by the # aggregate function. # Set working directory. setwd("rdatasets") # Read dataset with columns in fixed with format. # Specify widths, which are the column widths for each # variable. Use dummy variables for columns which are not # needed and which are discarded immediately. students <- read.fwf("students.txt", widths=c(10, 1, 5, 1, 4), col.names=c("dummy1", "gen", "dummy2", "yr", "gpa"))[ , c(-1, -3)] # Insert decimal point in gpa students$gpa <- students$gpa / 1000 print(students) # Compute group means by gender using aggregate function means1 <- as.matrix(aggregate(students$gpa, list(gender=students$gen), mean)) # Compute group means by year using aggregate function means2 <- as.matrix(aggregate(students$gpa, list(gender=students$yr), mean)) # Send graphs to PDF file. pdf("aggregate.pdf") # Create barplot of average GPA for each gender. barplot(means1[ ,2], names.arg=c("Female", "Male"), xlab="Gender", ylab="Average GPA", main="Average GPAs for Students at consolidated High") # Create barplot of average GPA for each year barplot(means2[ ,2], names.arg=c("Freshman", "Sophomore", "Junior", "Senior"), xlab="Gender", ylab="Average GPA", main="Average GPAs for Students at consolidated High") # Send graphics back to viewer. dev.off( )