从R中的对象提取值(不能通过“str”获得)

时间:2013-12-06 09:46:50

标签: r extract pca

我在从PCA对象中提取值时遇到问题。我需要“Comp.1”“方差比例”值。在此示例中,值为 0.7056111

我能够在摘要中看到它,但无法提取,因为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"

2 个答案:

答案 0 :(得分:5)

但是agstudy是如何找到它的? 这是我找出一些参数如何编码的一般方法

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, 

答案 1 :(得分:2)

您可以获得如下比例组件:

object <- princomp(pca_test)
vars <- object$sdev^2
vars/sum(vars)