## Slide 7
x1 <- rnorm(100)
x2 <- x1+rnorm(100)
plot(x1,x2,xlim=range(c(x1,x2)),ylim=range(c(x1,x2)),pch=19,col="gray")
X <- scale(cbind(x1,x2),scale=FALSE)
S <- svd(X)
U <- S$u
V <- S$v
d <- S$d
lines(d[1]/6*c(-V[1,1],V[1,1]),d[1]/6*c(-V[2,1],V[2,1]),col="green",lwd=3)
lines(d[2]/6*c(-V[1,2],V[1,2]),d[2]/6*c(-V[2,2],V[2,2]),col="green",lwd=3)

## Heart data
heart <- read.delim("../../data/heart.txt")
X <- scale(cbind(as.matrix(heart[,!is.element(names(heart),c("chd","famhist"))]),famhist=as.numeric(heart$famhist)))
n <- nrow(X)
S <- svd(X)
U <- S$u
V <- S$v
rownames(V) <- colnames(X)
d <- S$d

## Slide 10
p <- d^2/sum(diag(crossprod(X)))
plot(cumsum(p),ylim=c(0,1),type="o",pch=19,xlab="Component",ylab="Cumulative proportion explained")
abline(h=.75,col="gray")

## Slide 11
plot(d^2,ylim=c(0,d[1]^2),type="o",pch=19,xlab="Component",ylab=expression(d^2))
abline(h=n-1,col="gray")

## Slide 13
V[,1:4]

## Slide 15
plot(U[,1],U[,2],pch=19,xlab="PC1",ylab="PC2")
col <- c("gray","red")
plot(U[,1],U[,2],pch=19,col=col[1+heart$chd],xlab="PC1",ylab="PC2")

## Slide 16
col <- c(rgb(.75,.75,.75,alpha=0.5),rgb(1,0,0,alpha=0.5))
splom(U[,1:4],pch=16,col=col[1+heart$chd],cex=.5,xlab="")

## Some supplementary univariate analyses
boxplot(U[,1]~heart$chd)
t.test(U[,1]~heart$chd)
boxplot(U[,2]~heart$chd)
t.test(U[,2]~heart$chd)
boxplot(U[,3]~heart$chd)
t.test(U[,3]~heart$chd)
boxplot(U[,4]~heart$chd)
t.test(U[,4]~heart$chd)
