【问题标题】:Why am I only getting 1 and -1 from the cor() function in R?为什么我只能从 R 中的 cor() 函数中得到 1 和 -1?
【发布时间】:2017-12-31 22:29:37
【问题描述】:

我正在尝试使用 cor() 函数执行 Pearson 相关,但输出只给我 1 和 -1,而不是系数本身。所以当我用 corrplot() 绘制矩阵时,我只看到那些 1 和 -1 的值。我该如何解决? 我的数据集可以在here 找到,并在下面查看我的脚本:

##Must load the libraries we will need! IF you have not installed the packages, do that before you start. 
library("corrplot")
##Load in your datasets 
D1=BPT5test
##if you don't have a Y (i.e, you want the same thing to be in both axis), leave this blank
D2=
##Run the spearman correlation. If you want to do a Pearson, change "spearman to "pearson"
##If you have 0s in your dataset, set use = "complete.obs", if you have no 0s, set use = "everything"
CorTest=cor(D1, use = "everything", method = "pearson")
##Let's get to plotting! 
##Lots of changing you can do! 
#Method can be "circle" "square" "pie" "color"
#ColorRampPalette can be changed, "blue" being the negative, "White" being '0', and "red" being the positive
#Change the title to whatever you want it to be 
#tl.col is the color of your labels, this can be set to anything.. default is red
CorGraph=corrplot(CorTest, method = "circle", col = colorRampPalette(c("blue","white","red"))(200), title = "Pearson's Correlation of High-Fat Sugar at 8 weeks", tl.cex = .5, tl.col = "Black",diag = TRUE, cl.ratio = 0.2)

【问题讨论】:

    标签: r correlation


    【解决方案1】:

    您的数据集每个变量仅包含 2 个观察值。仅由两个观察值组成的任何两个变量之间的相关性始终为 -1 或 1。要亲自查看,请尝试运行 replicate(1e2, cor(rnorm(2), rnorm(2))),它会计算由两个观察值组成的两个变量之间的 100 个相关性。结果始终为 -1 或 1。

    【讨论】:

    • 谢谢你,显然我缺乏统计学知识占了上风。
    【解决方案2】:

    这是因为您按列只有两个观察值。

    test <- data.frame(a=c(1,2),b=c(2,3),c=c(4,-2))
    cor(test, use = "everything", method = "pearson")
       a  b  c
    a  1  1 -1
    b  1  1 -1
    c -1 -1  1
    

    你不能指望只有两个值的不同输出,检查Pearson correlation formula

    因为三个或更多,你会有更多的变化:

    test <- data.frame(a=c(1,2,3),b=c(2,3,5),c=c(4,-2,-10))
    cor(test, use = "everything", method = "pearson")
               a          b          c
    a  1.0000000  0.9819805 -0.9966159
    b  0.9819805  1.0000000 -0.9941916
    c -0.9966159 -0.9941916  1.0000000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2013-02-14
      • 1970-01-01
      相关资源
      最近更新 更多