如何从R的cor()相关分析计算P值和标准误差

14
我有一个关于编程的问题需要翻译:

我有data,每个条件(x和y)都包含54个样本。我是这样计算相关性的:

> dat <- read.table("http://dpaste.com/1064360/plain/",header=TRUE)
> cor(dat$x,dat$y)
[1] 0.2870823

请问在R的cor()函数中是否有原生方法可以生成相关性的标准误差和T检验的p值?

正如这个网页(第14.6页)所解释的那样。


4
也许你想要使用?cor.test代替。 - A5C1D2H2I1M1N2O1R2T1
2个回答

24

我认为你需要的是cor.test()函数,除了相关性标准误差之外,它将返回你所需的所有内容。但是,正如你所看到的,计算标准误差的公式非常简单,如果你使用cor.test,你就有了计算所需的所有输入。

使用示例数据(这样你可以自己与第14.6页上的结果进行比较):

> cor.test(mydf$X, mydf$Y)

    Pearson's product-moment correlation

data:  mydf$X and mydf$Y
t = -5.0867, df = 10, p-value = 0.0004731
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.9568189 -0.5371871
sample estimates:
       cor 
-0.8492663 

如果您愿意的话,也可以创建一个函数来包含相关系数的标准误差。
为了方便起见,这里是公式:
r = 相关估计值,n - 2 = 自由度,这两个值在上面的输出中很容易获得。因此,可以创建一个简单的函数:
cor.test.plus <- function(x) {
  list(x, 
       Standard.Error = unname(sqrt((1 - x$estimate^2)/x$parameter)))
}

然后按以下方式使用:

cor.test.plus(cor.test(mydf$X, mydf$Y))

这里,“mydf”被定义为:

mydf <- structure(list(Neighborhood = c("Fair Oaks", "Strandwood", "Walnut Acres",
  "Discov. Bay", "Belshaw", "Kennedy", "Cassell", "Miner", "Sedgewick", 
  "Sakamoto", "Toyon", "Lietz"), X = c(50L, 11L, 2L, 19L, 26L, 
  73L, 81L, 51L, 11L, 2L, 19L, 25L), Y = c(22.1, 35.9, 57.9, 22.2, 
  42.4, 5.8, 3.6, 21.4, 55.2, 33.3, 32.4, 38.4)), .Names = c("Neighborhood", 
  "X", "Y"), class = "data.frame", row.names = c(NA, -12L))

2
这个方程需要引用证明,对吧?(1-r^2)/sqrt(自由度)。参考链接:https://www.jstor.org/stable/2277400?seq=1#page_scan_tab_contents 或 https://www.tandfonline.com/doi/abs/10.1080/00220973.1956.11010555?journalCode=vjxe20。 - Samizdis

3

您不能简单地从返回值中获取检验统计量吗?当然,检验统计量是估计值/标准误差(estimate/se),因此您可以通过将估计值除以tstat来计算se:

在上面的答案中使用mydf

r = cor.test(mydf$X, mydf$Y)
tstat = r$statistic
estimate = r$estimate
estimate; tstat

       cor 
-0.8492663 
        t 
-5.086732 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接