Haley Haley - 3 years ago 62
R Question

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

I'm trying to perform a Pearson correlation with the cor() function, but the output only gives me 1 and -1, not the coefficient itself. So when I go to plot the matrix with corrplot(), I only see those 1 and -1 values. How do I fix this?
My dataset can be found here, and see my script down below:

##Must load the libraries we will need! IF you have not installed the packages, do that before you start.
##Load in your datasets
##if you don't have a Y (i.e, you want the same thing to be in both axis), leave this blank
##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)

Answer Source

Your dataset contains only 2 observations per variable. The correlation between any two variables consisting of only two observations is always -1 or 1. To see for yourself, try running replicate(1e2, cor(rnorm(2), rnorm(2))) which calculates 100 correlations between two variables consisting of two observations. The result is always -1 or 1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download