문제

I have a problem with extracting value from PCA object. I need "Proportion of Variance" value from "Comp.1". In this example it is value 0.7056111.

I am able to see it in summary, but unable to extract because it is not present in str(pca_test).

pca_test<-data.frame(var1=rnorm(20), var2=rnorm(20))
summary(princomp(pca_test))

Importance of components:
                          Comp.1    Comp.2
Standard deviation     1.0200426 0.6588649
Proportion of Variance 0.7056111 0.2943889
Cumulative Proportion  0.7056111 1.0000000


# value 0.7056111 is absent here
> str(summary(princomp(pca_test)))
List of 9
 $ sdev          : Named num [1:2] 1.02 0.659
  ..- attr(*, "names")= chr [1:2] "Comp.1" "Comp.2"
 $ loadings      : loadings [1:2, 1:2] 0.289 0.957 -0.957 0.289
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "var1" "var2"
  .. ..$ : chr [1:2] "Comp.1" "Comp.2"
 $ center        : Named num [1:2] 0.1497 -0.0897
  ..- attr(*, "names")= chr [1:2] "var1" "var2"
 $ scale         : Named num [1:2] 1 1
  ..- attr(*, "names")= chr [1:2] "var1" "var2"
 $ n.obs         : int 20
 $ scores        : num [1:20, 1:2] -1.8965 1.4866 -1.5019 0.0841 0.4751 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:2] "Comp.1" "Comp.2"
 $ call          : language princomp(x = pca_test)
 $ cutoff        : num 0.1
 $ print.loadings: logi FALSE
 - attr(*, "class")= chr "summary.princomp"
도움이 되었습니까?

해결책

But how did agstudy find it out? Here my general approach to find out how some parameter is coded

pca_test<-data.frame(var1=rnorm(20), var2=rnorm(20))
pc = princomp(pca_test)
str(pc) # proportion not found
sp = summary(pc)
str(sp) # The proportion is still not there
# It is of class summary.princomp
# So it probably comes with the print
# This is naughty behavioR, the print function should not compute,
# but rather focus on display
getAnywhere(print.summary.princomp)
# There it is, at the top
#vars <- x$sdev^2
#vars <- vars/sum(vars)
#cat("Importance of components:\n")
#print(rbind(`Standard deviation` = x$sdev, `Proportion of Variance` = vars, 

다른 팁

You can get proportion components like this :

object <- princomp(pca_test)
vars <- object$sdev^2
vars/sum(vars)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top