簡體   English   中英

為什么我只從R中的cor()函數得到1和-1?

[英]Why am I only getting 1 and -1 from the cor() function in R?

我正在嘗試使用cor()函數執行Pearson相關,但是輸出僅給出1和-1,而不給出系數本身。 因此,當我使用corrplot()繪制矩陣時,我只看到那些1和-1值。 我該如何解決? 我的數據集可以在此處找到,並在下面查看我的腳本:

##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)

您的數據集每個變量僅包含2個觀察值。 僅由兩個觀察值組成的任意兩個變量之間的相關性始終為-1或1。要親自查看,請嘗試運行replicate(1e2, cor(rnorm(2), rnorm(2))) ,該操作將計算兩個變量之間的100個相關性兩個觀察結果。 結果始終為-1或1。

這是因為按列您只有兩個觀察值。

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相關公式

由於三個或更多,您將擁有更多的變化:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM