w3resource

R programming - Create Correlation Matrix from Dataframe


Write a R program to create a correlation matrix from a dataframe of same data type.

Sample Solution:

R Programming Code:

# Create a dataframe with three columns x1, x2, and x3, each containing 5 random normal values
d = data.frame(x1=rnorm(5),
               x2=rnorm(5),
               x3=rnorm(5))

# Print a message indicating that the following output is the original dataframe
print("Original dataframe:")   

# Print the content of the dataframe
print(d)

# Calculate the correlation matrix of the dataframe
result = cor(d) 

# Print a message indicating that the following output is the correlation matrix
print("Correlation matrix:")

# Print the correlation matrix
print(result)

Output:

[1] "Original dataframe:"
          x1         x2         x3
1 -0.0905430  1.7469241 -0.1360780
2 -0.1936120  0.9111132  0.5282113
3  0.7688536 -0.9413734 -0.8032169
4  2.0247769 -0.3096149 -0.8617996
5 -0.1824352  1.6179504 -0.2554897
[1] "Correlation matrix:"
           x1         x2         x3
x1  1.0000000 -0.7422855 -0.7789883
x2 -0.7422855  1.0000000  0.6600909
x3 -0.7789883  0.6600909  1.0000000                

Explanation:

  • Create DataFrame:
    • d = data.frame(x1=rnorm(5), x2=rnorm(5), x3=rnorm(5))
      • Creates a dataframe d with three columns (x1, x2, x3).
      • Each column contains 5 random values drawn from a normal distribution (rnorm(5)).
  • Print DataFrame Label:
    • print("Original dataframe:")
      • Prints a label indicating that the next output will display the original dataframe.
  • Print DataFrame:
    • print(d)
      • Prints the contents of the dataframe d.
  • Calculate Correlation Matrix:
    • result = cor(d)
      • Computes the correlation matrix for the dataframe d, showing pairwise correlations between columns.
  • Print Correlation Matrix Label:
    • print("Correlation matrix:")
      • Prints a label indicating that the next output will display the correlation matrix.
  • Print Correlation Matrix:
    • print(result)
      • Prints the calculated correlation matrix.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to convert a matrix to a 1 dimensional array.
Next: Write a R program to convert a given matrix to a list of column-vectors.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.