Correlation of One Variable to All Others in R (Example)

 

In this R tutorial you’ll learn how to calculate the correlation of one data frame column to all the others.

The page contains this:

It’s time to dive into the example…

 

Creation of Exemplifying Data

Consider the following example data:

set.seed(6529489)                                 # Create example data
data <- data.frame(x1 = rnorm(100),
                   x2 = rnorm(100),
                   x3 = rnorm(100),
                   x4 = rnorm(100))
head(data)                                        # Print head of example data

 

table 1 data frame correlation one variable all others r

 

Table 1 shows that our example data is constructed of the four columns “x1”, “x2”, “x3”, and “x4”.

 

Example: Calculate Correlation of One Variable to All Others Using cor() Function

In this example, I’ll demonstrate how to get the Pearson correlation coefficient between a particular data frame variable with all the other variables in this data frame.

To achieve this, we can apply the cor and colnames functions as shown below:

data_cor <- cor(data[ , colnames(data) != "x1"],  # Calculate correlations
                data$x1)
data_cor                                          # Print correlation values

 

table 2 matrix correlation one variable all others r

 

As visualized in Table 2, the previous code has managed to construct a correlation matrix for only one of the columns in our data set.

 

Video, Further Resources & Summary

If you need more information on the R codes of this article, you might watch the following video on my YouTube channel. I demonstrate the R programming codes of this tutorial in the video:

 

The YouTube video will be added soon.

 

In addition, you may read the related articles on Statistics Globe. A selection of articles about topics such as ggplot2, variables, lists, and graphics in R is shown below.

 

This tutorial has demonstrated how to compute the correlation of one data frame column to many others in R. If you have additional questions and/or comments, please let me know in the comments below.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top