To create a correlation matrix for a data frame in R, you can use the cor() function. A correlation matrix is a table showing correlation coefficients between variables.

In this article, we will explore how to create a correlation matrix for an R data frame using the cor() function.

Method: Use cor() Function

The cor() function in R is used to calculate the correlation matrix for a data frame. Here’s the syntax:

cor(df)

The following example shows how to create a correlation matrix in R using the cor() function.

Using cor() Function

Let’s see how we can use the cor() function to create a correlation matrix:

# Create data frame
df <- data.frame(Value = c(108, 120, 135, 95, 98, 105),
                 Reading = c(110, 97, 91, 89, 80, 85))

# Correlation matrix
matrix <- cor(df)

# Print correlation matrix
print(matrix)

Output: 👇️

            Value   Reading
Value    1.0000000 0.9149910
Reading  0.9149910 1.0000000

In this example, the cor() function calculates the correlation matrix for the Value and Reading columns of the data frame.