# Read in data
titanic <- read.delim("http://myweb.uiowa.edu/pbreheny/data/titanic.txt")
head(titanic)
nrow(titanic)
ncol(titanic)
dim(titanic)

# table
table(titanic$Class)

# Proportions
tab <- table(titanic$Class)
tab/nrow(titanic)
prop.table(tab)

# Percentages
round(100*prop.table(tab), 1)

# Two way table of class and survival
with(titanic, table(Class, Survived))

# Two way proportions
tab <- with(titanic, table(Class, Survived))
prop.table(tab)    ## Overall proportion
prop.table(tab, 1) ## Row-wise proportion
prop.table(tab, 2) ## Column-wise proportion

# Three way table of class
tab <- with(titanic, table(Class, Survived, Sex))
tab
prop.table(tab, c(1,3))

# barplot
tab <- table(titanic$Class)
barplot(tab)

# stacked barplot
tab <- with(titanic, table(Survived, Class))
barplot(tab, legend=TRUE, args.legend=list(x="topleft"))

# Loading the lattice package
require(lattice) ## or library(lattice)

# lattice barchart
tab <- table(titanic$Class)
barchart(tab)

# lattice stacked barplot
tab <- with(titanic, table(Class, Survived))
barchart(tab, auto.key=TRUE)

# Conditioning
tab <- with(titanic, table(Class, Sex, Survived))
barchart(tab, auto.key=TRUE)

# Unequal scales
barchart(tab, auto.key=TRUE, scales="free")

# Install ggplot2
## install.packages("ggplot2")

# Plotting with ggplot2
require(ggplot2)
qplot(Class, data=titanic, fill=Survived) + facet_grid(Age~Sex, scales="free")
