[R] PCA projection graphic

Cleber Nogueira Borges
Thu, 29 May 2008 15:06:10 -0000

Hello all,

I am trying make an graphic of 1? PC projection, but I not get success
in adaption of code at ref[1].
The code make a 2? PC projection...{by mistake, I guess...}

Anyone can help me? Thanks in advance.
Cleber

####
# adaption code :: ref[1]="Statistics with R", cap.09;
http://zoonek2.free.fr/UNIX/48_R/09.html

# OLS regression
 n <- 10
 x<-1:n; y<-x+rnorm(n,0,2)
 plot(x,y); abline(r<-lm(y~x))
 segments(x, y, x, r$fitted.values,col="red")

# PCA
# 1? pc
r <- princomp(cbind(x,y))
b <- r$loadings[2,1] / r$loadings[1,1]
a <- r$center[2] - b * r$center[1]
abline(a,b, col='blue')

## 2? pc
b <- r$loadings[2,2] / r$loadings[1,2]
a <- r$center[2] - b * r$center[1]
abline(a,b, col='blue')



# Change-of-base matrix
u <- r$loadings
# Projection onto the first axis  <<< problem here... (??)
p <- matrix( c(1,0,0,0), nrow=2 )

X <- rbind(x,y)
X <- r$center + solve(u, p %*% u %*% (X - r$center))

plot(x,y); abline(a,b, col='blue')
segments( x, y, X[1,], X[2,] )      ### Projection in 2? pc  :-( :-( :-(