【问题标题】:Extract values (not available via "str") from object in R从 R 中的对象中提取值(不能通过“str”获得)
【发布时间】:2013-12-06 09:46:50
【问题描述】:

我在从 PCA 对象中提取值时遇到问题。我需要 "Comp.1" 中的 "Proportion of Variance" 值。在本例中,它的值为 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"

【问题讨论】:

  • 这是在 stats:::print.summary.princomp 中计算的

标签: r extract pca


【解决方案1】:

但是,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, 

【讨论】:

    【解决方案2】:

    你可以像这样得到比例分量:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 2014-06-11
      相关资源
      最近更新 更多