Reputation: 135
I want to have the summary of the princomp PCA (has to be princomp) as a dataframe so that I can format the table with kable for a report.
Here is the code I tried to use, it should be clear from this what I want to do;
kable( as.data.frame(summary(pca.data)) )
I get this error:
Error in as.data.frame.default(summary(pca.data)) : cannot coerce class ""summary.princomp"" to a data.frame
EDIT: I want the output of sum.data as a dataframe so I can use the kable function to format it.
library("knitr")
library("kableExtra")
set.seed(1)
data <- data.frame(
X = sample(1:10), X2 = sample(1:10), X3 = sample(1:10), X4 = sample(1:10),
X5 = sample(1:10)
)
pca.data <- princomp(data, cor=TRUE)
sum.data <- summary(pca.data)
kable(as.data.frame(sum.data))
Upvotes: 2
Views: 1195
Reputation: 206446
Assuming you are trying to get the following table
Importance of components:
Comp.1 Comp.2 Comp.3 Comp.4 Comp.5
Standard deviation 1.4126051 1.1441266 0.9542661 0.63918520 0.61346533
Proportion of Variance 0.3990906 0.2618052 0.1821247 0.08171154 0.07526794
Cumulative Proportion 0.3990906 0.6608958 0.8430205 0.92473206 1.00000000
that's not actually stored anywhere and is only created when you run the stats:::print.summary.princomp
function. You can extract the part of that function that makes that table. For example
pca_importance <- function(x) {
vars <- x$sdev^2
vars <- vars/sum(vars)
rbind(`Standard deviation` = x$sdev, `Proportion of Variance` = vars,
`Cumulative Proportion` = cumsum(vars))
}
so now you have an object that ktable can use
kable( pca_importance(sum.data) )
Upvotes: 5