【问题标题】:Using cor() on the entire data set versus two variables in R在整个数据集上使用 cor() 与 R 中的两个变量
【发布时间】:2021-01-06 17:38:54
【问题描述】:

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

但是,如果我运行 cor.test(metals$metal1,metals$metal2, method = "spearman", use = "complete.obs"),它会返回 .3529。所有其他对出现相同的差异。有人能解释一下为什么或者这两种方法之间是否存在根本区别吗?

【问题讨论】:

  • 这与“complete.obs”的使用有关。完整的观察是您对每个变量都有值的观察。如果您只考虑 2 个变量,则可能会有更完整的观察结果。如果将use 设置为parwise.complete.obs,应该会得到相同的结果。
  • 非常感谢!
  • cor 的默认测试方法是 pearson。您已将 spearman 用于cor.test。尝试将其更改为 pearson

标签: r correlation stat


【解决方案1】:

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.test(metals$metal1,metals$metal2, method = "spearman", use = "complete.obs")。 (尽管cor 的文档确实说我们可以同时给出 x 和 y 值)
【解决方案2】:

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

从包MASS中的波士顿数据查看这个示例。

# 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, boston$zn, method = "spearman"): Cannot
#> compute exact p-value with ties
s$estimate
#>        rho 
#> -0.5716602

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多