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 will be discarded later. students <- read.fwf("students.txt", widths=c(10, 1, 5, 1, 4), col.names=c("dummy1", "gen", "dummy2", "yr", "dummy3")) print(students) # Discard unwanted columns in dummy variables. # The index c(2, 4) means keep variables 2 and 4. students2 <- students[ , c(2, 4)] print(students2) # Summarize data with table function. # You could have used the following line instead: # tab <- table(students[ , c(2, 4)]) tab <- table(students2) print(tab) # Send graphs to PDF file. pdf("students.pdf") # Create stacked bar plot. font.sub=2 means bold font. barplot(tab, main="Students in Consolidated High", xlab="Year in School", ylab="Number of Students", names.arg=c("Freshman", "Sophomore", "Junior", "Senior"), font.main=2, col=c("red", "blue")) legend(x="topright", legend=c("Female", "Male"), fill=c("red", "blue")) # Create side-by-side barplot. barplot(tab, main="Students in Consolidated High", xlab="Year in School", ylab="Number of Students", names.arg=c("Freshman", "Sophomore", "Junior", "Senior"), font.main=2, beside=TRUE, col=c("red", "blue")) legend(x="topright", legend=c("Female", "Male"), fill=c("red", "blue")) # Send graphics back to viewer. dev.off( )