Skip to content

Instantly share code, notes, and snippets.

@jalapic
Created April 6, 2015 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jalapic/74d2f06418947009a5d1 to your computer and use it in GitHub Desktop.
Save jalapic/74d2f06418947009a5d1 to your computer and use it in GitHub Desktop.
PCA
#### Some simple Principal Components Analysis
# from Gaston Sanchez website
USArrests
# PCA with function prcomp
pca1 = prcomp(USArrests, scale. = TRUE)
# sqrt of eigenvalues
pca1$sdev
head(pca1$rotation)
head(pca1$x)
### Let's Plot
# load ggplot2
library(ggplot2)
# create data frame with scores
scores = as.data.frame(pca1$x)
# plot of observations
ggplot(data = scores, aes(x = PC1, y = PC2, label = rownames(scores))) +
geom_hline(yintercept = 0, colour = "gray65") +
geom_vline(xintercept = 0, colour = "gray65") +
geom_text(colour = "tomato", alpha = 0.8, size = 4) +
ggtitle("PCA plot of USA States - Crime Rates")
## Circle of Correlations
# function to create a circle
circle <- function(center = c(0, 0), npoints = 100) {
r = 1
tt = seq(0, 2 * pi, length = npoints)
xx = center[1] + r * cos(tt)
yy = center[1] + r * sin(tt)
return(data.frame(x = xx, y = yy))
}
corcir = circle(c(0, 0), npoints = 100)
# create data frame with correlations between variables and PCs
correlations = as.data.frame(cor(USArrests, pca1$x))
# data frame with arrows coordinates
arrows = data.frame(x1 = c(0, 0, 0, 0), y1 = c(0, 0, 0, 0), x2 = correlations$PC1,
y2 = correlations$PC2)
# geom_path will do open circles
ggplot() + geom_path(data = corcir, aes(x = x, y = y), colour = "gray65") +
geom_segment(data = arrows, aes(x = x1, y = y1, xend = x2, yend = y2), colour = "gray65") +
geom_text(data = correlations, aes(x = PC1, y = PC2, label = rownames(correlations))) +
geom_hline(yintercept = 0, colour = "gray65") + geom_vline(xintercept = 0,
colour = "gray65") + xlim(-1.1, 1.1) + ylim(-1.1, 1.1) + labs(x = "pc1 axis",
y = "pc2 axis") + ggtitle("Circle of correlations")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment