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
特别是,如何处理这些值 0.0001517 和 -0.188074 ,以便我可以将它们存储起来进行进一步分析?
答案 0 :(得分:29)
您可以使用测试对象的$
子集。相关名称为p.value
和estimate
。
> 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
> tst$p.value
[1] 0.6818076
> tst$estimate
rho
0.1515152
修改强>
其他答案指出,您可以使用str
调查对象的结构,以查找要用于$
子集的名称。您还可以使用names
找到名称:
> names(tst)
[1] "statistic" "parameter" "p.value" "estimate" "null.value"
[6] "alternative" "method" "data.name"
要考虑的另一件事是您正在查看对象的打印版本,并且打印方法可能正在执行某些计算(在这种情况下不是这样)。您可以使用class(tst)
检查对象类,该对象类显示它属于类htest
。 print.htest
是相关的打印方法,但这是不可见的,因此请使用getAnywhere(print.htest)
进行查看。
答案 1 :(得分:17)
test.res <- cor.test(x,y,method="spearman", exact=F)
使用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"
使用$表示法可以获得其中任何一个。如果您正在寻找获得p.value的话,请使用以下内容:
test.res$p.value
答案 2 :(得分:6)
test.res <- cor.test(x,y,method="spearman", exact=F)
test.res[1:8]
你正在寻找的东西将在那里。
为特定值添加另一个索引前缀,如下所示:
test.res[1][1]
找到一个特定的元素,你可以str(test.res)
找到它的位置并在上面替换,例如test.res[1][5]