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:
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. Test your Programming skills with w3resource's quiz.
Next: Write a R program to convert a given matrix to a list of column-vectors.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics