[R] PCA analysis

Monica Pisica pisicandru at hotmail.com
Wed Jun 18 15:28:29 CEST 2008


Monna,

The way i do it is to re-create the biplot for the PCA ..... I am attaching my code (i am sure this can be done even easier ..... but this works as well) where i am using pca() function from labdsv and my data is called veg1.

library (labdsv)
pca.1<-pca(veg1,cor=TRUE)

# The scores are what are typically plotted in a PCA "ordination", but we will scale them between -1 and 1 so you can plot together with loadings

scores <- pca.1$scores
nrows <- nrow(scores)
ncols <- ncol(scores)

#re-scaling 

for (i in 1:nrows) {
	for (j in 1:ncols){
if (pca.1$scores[i,j] < 0) scores[i,j] <- (-1)*(pca.1$scores[i,j])/min(pca.1$scores) else scores[i,j] <- pca.1$scores[i,j]/max(pca.1$scores)
}}

pc1 <- scores[,1]
pc2 <- scores[,2]
plot(pc1, pc2, pch=16, cex=2, col ="paleturquoise", xlim = c(-1, 1), xlab = "PC1", ylab = "PC2",main = "Principal Component Analysis, Region A")

## here you can change pch as a function of your values so the points will have different sizes - if you wish - but the sizes need to be a vector of numbers ## and not characters and .... your numbers are too big so maybe you should scale them somehow .... let's say between 1 and 3 or whatever .....

abline(v=0, lty=2, col="green")
abline(h=0, lty=2, col="green")

# add the loadings

loadings <- pca.1$loadings
load1 <- loadings[,1]
load2 <- loadings[,2]
c0 <- rep(0,length(load1))
d0 <- rep(0,length(load1))
c1 <- load1
d1 <- load2
segments(c0,d0,c1,d1, col = "grey")

load <- cbind(load1, load2)
points(load, pch=17, cex = 2, col = "darkblue")

identify(load[,1],load[,2], dimnames(load)[[1]], col = "deeppink3", font = 2)

I hope this helps,

Monica



_________________________________________________________________
The other season of giving begins 6/24/08. Check out the i’m Talkathon.



More information about the R-help mailing list