Home » R13 June 2017

R: Correlation – Finding out relation between data

This article shows how to calculate correlation between two data/variables using R programming language.

Correlation calculates the relation between two variables.

Positive Correlation: If the value of one variable increases with the increase in value of the another variable then the two variables are said to be positively correlated.

Negative Correlation: If the value of one variable decreases with the decrease in value of the another variable then the two variables are said to be negatively correlated.

For this example, we have two variables: height and weight. These variables have some values and they have a relation. In the below example data: 60kg of weight has 150cm in height, 70kg in weight has 160cm in height, and so on.

To calculate correlation between two variables, we use cor() function. It shows how positively or negatively the two variables are correlated.

We can also specify the correlation method which can be either pearson, spearman or kendall.

Below, we create a data frame of height and weight. Then, we calculate the correlation of the data frame. This is useful to show how height is correlated with weight and how weight is correlated with height in a single result.

Below, we create a new variable named exercise. Exercise variable contains exercise done by people in number of minutes. So, taking all three variables, it can be observed that people with 60kg of weight has 150cm in height and does 10 minutes of exercise, 70kg in weight has 160cm in height and does 7 minutes of exercise, and so on.

Now, we calculate the correlation between three different variables: height, weight, and exercise. We use data frame to show the result. We show how height is correlated with weight and exercise, how weight is correlated with height and exercise, and how exercise is correlated with height and weight.

Plotting two graphs. One with the correlation between height and exercise. And, the other with correlation between weight and exercise.

Hope this helps. Thanks.

R

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed