How to Create a Correlation Matrix for R DataFrame

To create a correlation matrix for a DataFrame in R:

correlation_matrix <- cor(df)

Steps to Create a Correlation Matrix for R DataFrame

Step 1: Create R DataFrame

Here is a simple DataFrame in R with 3 columns:

# Create the DataFrame
df <- data.frame(
  A = c(45, 37, 42, 35, 39),
  B = c(38, 31, 26, 28, 33),
  C = c(10, 15, 17, 21, 12)
)

# Print the DataFrame
print(df)

The resulted DataFrame:

   A  B  C
1 45 38 10
2 37 31 15
3 42 26 17
4 35 28 21
5 39 33 12

Step 2: Build the Correlation Matrix in R

The full script to build the Correlation Matrix in R:

# Create the DataFrame
df <- data.frame(
  A = c(45, 37, 42, 35, 39),
  B = c(38, 31, 26, 28, 33),
  C = c(10, 15, 17, 21, 12)
)

# Build the correlation matrix
correlation_matrix <- cor(df)

# Display the correlation matrix
print(correlation_matrix)

The final Correlation Matrix:

           A          B          C
A  1.0000000  0.5184571 -0.7018864
B  0.5184571  1.0000000 -0.8609410
C -0.7018864 -0.8609410  1.0000000

Leave a Comment