从任何统计测试中获取单个值(例如,cor.test中的spearman rho的值)

Riv*_*ivo 17 r

R中的统计测试输出许多描述.虽然它们很有用,但我们如何才能输出或提取单个值?

> cor.test(x,y,method="spearman", exact=F)

        Spearman's rank correlation rho

data:  x and y 
S = 12767993, p-value = 0.0001517
alternative hypothesis: true rho is not equal to 0 
sample estimates:
      rho 
-0.188074 
Run Code Online (Sandbox Code Playgroud)

特别是,怎么做才能得到这些值0.0001517-0.188074所以我可以存储它们进行进一步分析?

Jam*_*mes 29

您可以使用$测试对象的子集.相关名称是p.valueestimate.

> tst<-cor.test(1:10,rnorm(10),method="spearman")
> tst

        Spearman's rank correlation rho

data:  1:10 and rnorm(10) 
S = 140, p-value = 0.6818
alternative hypothesis: true rho is not equal to 0 
sample estimates:
      rho 
0.1515152 
Run Code Online (Sandbox Code Playgroud)

.

> tst$p.value
[1] 0.6818076
> tst$estimate
      rho 
0.1515152 
Run Code Online (Sandbox Code Playgroud)

编辑

其他答案指出,您可以调查对象的结构,str以查找要用于$子集化的名称.您还可以找到以下名称names:

> names(tst)
[1] "statistic"   "parameter"   "p.value"     "estimate"    "null.value" 
[6] "alternative" "method"      "data.name" 
Run Code Online (Sandbox Code Playgroud)

另一件需要考虑的事情是你正在查看对象的打印版本,并且打印方法可能正在执行一些计算(在这种情况下不是这样).您可以检查class(tst)显示它是类的对象类htest.print.htest是相关的打印方法,但这是不可见的,所以用getAnywhere(print.htest)它来查看它.

  • 虽然已经在其他答案中处理过了,但我想你也可以指出`str()`会显示可以使用`$`符号调用的变量.还有一个技巧 - 你有时只在`summary`和`print`中看到值(它们是根据来自对象的数据计算的),而不是在对象本身中.然后,您必须子集,例如`summary(object)$ variable`. (5认同)

Mar*_*ark 17

test.res <- cor.test(x,y,method="spearman", exact=F)
Run Code Online (Sandbox Code Playgroud)

使用str(test.res)查看对象的结构

> str(test.res)
List of 8
 $ statistic  : Named num 182
  ..- attr(*, "names")= chr "S"
 $ parameter  : NULL
 $ p.value    : num 0.785
 $ estimate   : Named num -0.103
  ..- attr(*, "names")= chr "rho"
 $ null.value : Named num 0
  ..- attr(*, "names")= chr "rho"
 $ alternative: chr "two.sided"
 $ method     : chr "Spearman's rank correlation rho"
 $ data.name  : chr "1:10 and rnorm(10)"
 - attr(*, "class")= chr "htest"
Run Code Online (Sandbox Code Playgroud)

使用$表示法可以获得其中任何一个.如果您正在寻找获得p.value,请使用以下内容:

test.res$p.value
Run Code Online (Sandbox Code Playgroud)


Joh*_*ohn 6

test.res <- cor.test(x,y,method="spearman", exact=F)
test.res[1:8]
Run Code Online (Sandbox Code Playgroud)

你在寻找什么将在那里.

对于特定值,添加另一个索引前缀如下:

test.res[1][1]
Run Code Online (Sandbox Code Playgroud)

找到一个特定的元素,你可以str(test.res)找到它的位置,并在上面替代,如test.res[1][5]