In a shiny app I am building I want to show only the explained variance and the model fit measure of the output of the principal function (of the r package psych). I investigated the structure of the output, but unfortenately (and perhaps a bit strangely) I couldn't find the exact spot of these values. Does anyone have an idea how to obtain these values from the output?
-
Can you explain the term "model fit measure"? – jlhoward Apr 29 '14 at 19:54
-
I think I mean the "Fit based upon off diagonal values". Or am I completely wrong about presuming this is a model fit measure? – rdatasculptor Apr 29 '14 at 20:04
1 Answers
First, if you expect help, you should provide a reproducible example, which includes a sample of your data. This is why your question was downvoted (not by me though).
The variance due to the ith principal component is given by the ith eigenvalue of the correlation matrix. Since the PCs are orthogonal (uncorrelated) by definition, the total variance is given by the sum of the individual variances = the sum of the eigenvalues. The eigenvalues are returned in principal(...)$values
. So the proportion of total variance explained by each PC is given by:
prop.table(principal(...)$values)
Since you didn't provide any data, I'll use the built-in mtcars
dataset for a working example:
library(psych)
df <- mtcars[c("hp","mpg","disp","wt","qsec")]
pca <- principal(df)
prop.table(pca$values)
# [1] 0.73936484 0.19220335 0.03090626 0.02623083 0.01129473
So the first PC explains 74% of the total variation, the second PC explains 19%, etc. This agrees perfectly with the result using prcomp(...)
, keeping in mind that principal(...)
scales by default, while prcomp(...)
does not.
pc <- prcomp(df,scale.=T)
summary(pc)
# Importance of components:
# PC1 PC2 PC3 PC4 PC5
# Standard deviation 1.9227 0.9803 0.39310 0.36215 0.23764
# Proportion of Variance 0.7394 0.1922 0.03091 0.02623 0.01129
# Cumulative Proportion 0.7394 0.9316 0.96247 0.98871 1.00000
The parameter "Fit based upon off diagonal values" is given in principal(...)$fit.off
, as explained in the documentation.
-
Thank you so much for your answer and your effort! (And sorry for not giving reproducible example.) your solution in using "prop.table" was really something i would have never thought of. – rdatasculptor Apr 29 '14 at 21:23
-