R Correlation
Correlation
In the Scatter Plot chapter, the plot of 12 cars seemed to show that the newer the car, the faster it drives.
Correlation turns that kind of relationship into one number, between -1 and 1:
| Value | Meaning |
|---|---|
| 1 | Perfect positive relationship: when one value goes up, the other goes up too |
| 0 | No relationship |
| -1 | Perfect negative relationship: when one value goes up, the other goes down |
The closer the value is to 1 or -1, the stronger the relationship.
The cor() Function
Do heavier cars drive fewer miles per gallon? First, look at the weight (wt) and the miles per gallon (mpg) of the cars in the mtcars data set in a scatter plot:
Example
Data_Cars <- mtcars
plot(Data_Cars$wt, Data_Cars$mpg, main = "Weight and Miles per Gallon", xlab = "Weight", ylab = "Miles per gallon")
Result:
The dots go down from left to right. Now use the cor() function to measure the relationship:
Example
Data_Cars <- mtcars
cor(Data_Cars$wt, Data_Cars$mpg)
Result:
[1] -0.8676594The result is close to -1, which is a strong negative relationship: the heavier the car, the fewer miles it drives per gallon.
Positive Correlation
The weight and the horsepower (hp) have a positive relationship: heavier cars often have stronger engines:
Example
Data_Cars <- mtcars
cor(Data_Cars$wt, Data_Cars$hp)
Result:
[1] 0.6587479Note: A correlation does not prove that one thing causes the other. It only shows that the two values often change together.
Covariance
The cov() function finds the covariance. It also shows if two values go up and down together (positive) or in opposite directions (negative):
Example
Data_Cars <- mtcars
cov(Data_Cars$wt, Data_Cars$mpg)
Result:
[1] -5.116685But the size of the covariance depends on the units of the data, so it is hard to say if a number is big or small. That is why correlation is used more often: it is the covariance scaled to a number between -1 and 1.