0

I'm new to R world and I was trying to do a pca on a dataset; I used rgl library for 3D plots but when I run my code il plots everithing but lines3d and planes3d.

I expected to have a clear result because it was the exact same code as the teacher's one but what I got was only the plots of the points3d function; the problem lies when I use the functions lines3d and planes3d

That's the code I used:

library(rgl)
library(mvtnorm)

#matrix
nobs = 100
sig = rbind(c(9, 1, 1), c(1, 4, 1), c(1, 1, 1))   
mu = c(0, 2, 3)    
X = rmvnorm(nobs,mu,sig)     
X

#mean
M <- colMeans(X)    
M

#variance matrix
S <- cov(X)        
S # eigen(S)


R = cor(X)
R


open3d()                    
points3d(X, asp=1, size=4)   
axes3d()

#principal components
PC = princomp(X)            
PC

PC$loadings       
                   
eigen(S)$vectors

PC$scores       

open3d()
points3d(X, asp=1, size=4)
axes3d()

#display mean on the graphic 
points3d(t(M), col='red', size=6)

#lines to connect the mean to the observations
for(i in 1:nobs)                  
  lines3d(rbind(X[i,], M))      

#first principal component
open3d()
points3d(X, asp=1, size=4)
axes3d()

PC1 <- NULL
for (i in 1:nobs) PC1 <- rbind(PC1, PC$loadings[,1]*PC$scores[i,1] + M)
points3d(PC1, col = 'red', size = 6)

for (i in 1:nobs) lines3d(rbind(X[i,], PC1[i,]), col = 'blue')

lines3d(rbind(M + 2*PC$sdev[1]*PC$loadings[,1], M - 2*PC$sdev[1]*PC$loadings[,1]), col = 'green')

#second principal component
open3d()
points3d(X, asp=1, size=4)
axes3d()

PC12 <- NULL
for(i in 1:nobs)PC12 <- rbind(PC12, PC$loadings[,1]*PC$scores[i,1] + PC$loadings[,2]*PC$scores[i,2] + M)
points3d(PC12, col='red', size=6)

for(i in 1:nobs)lines3d(rbind(X[i,], PC12[i,]),col='blue')


library(pracma)
normal = cross(PC$loadings[,1],PC$loadings[,2])
planes3d(a = normal,d = - normal %*% M, col = "orange")

0 Answers0