在整个数据集上使用 cor() 与 R 中的两个变量

问题描述

我有一个名为“Metals”的数据集,其中包含许多变量,我想查看每对的 spearman 相关性 rho。当我运行 cor(Metals,method = "spearman",use = "complete.obs") 时,我得到一个值,比如 Metal1 和 Metal2,它是 0.143。

但是,如果我运行 cor.test(Metals$Metal1,Metals$Metal2,use = "complete.obs"),它返回 0.3529。所有其他对都出现相同的差异。有人可以解释为什么或者这两种方法之间是否存在根本区别吗?

解决方法

cor 的文档没有提到使用公式作为输入的可能性:

Arguments
x   a numeric vector,matrix or data frame.

y   NULL (default) or a vector,matrix or data frame with compatible dimensions to x. The default is equivalent to y = x (but more efficient).
,

我认为这是由使用的不同测试方法造成的。 cor 使用 pearson,您已经将 spearman 用于 cor.test

从包 MASSBoston 数据中查看此示例。

# library(MASS)
boston <- MASS::Boston

round(cor(boston),2)
#> not shown

round(cor(boston[1:2]),2)
#>      crim   zn
#> crim  1.0 -0.2
#> zn   -0.2  1.0


# The spearman-version of cor.test
cor.test(boston$crim,boston$zn,method = 'spearman') ->s
#> Warning in cor.test.default(boston$crim,method = "spearman"): Cannot
#> compute exact p-value with ties
s$estimate
#>        rho 
#> -0.5716602

# The pearson-version of cor.test
cor.test(boston$crim,method = 'pearson') -> p
p$estimate
#>        cor 
#> -0.2004692