R – Correlation Matrix
To find Correlation Matrix a given matrix in R, call cor() function, and pass given matrix as argument to it. The function returns the Correlation Matrix for the supplied matrix.
In this tutorial, we will learn how to compute Correlation Matrix using cor() function, with the help of examples.
Syntax
The syntax to find correlation matrix for matrix A
is
</>
Copy
cor(A)
Return Value
cor() function returns a matrix.
Examples
In the following program, we will create a matrix A
and find its Correlation Matrix using cor() function.
example.R
</>
Copy
data <- c(1, 4, 0, -1, 0, 1, 2, 6, -1)
A <- matrix(data, nrow = 3, ncol = 3)
A_C <- cor(A)
print("Matrix A")
print(A)
print("Correlation Matrix of A")
print(A_C)
Output
[1] "Matrix A"
[,1] [,2] [,3]
[1,] 1 -1 2
[2,] 4 0 6
[3,] 0 1 -1
[1] "Correlation Matrix of A"
[,1] [,2] [,3]
[1,] 1.0000000 -0.2401922 0.9803156
[2,] -0.2401922 1.0000000 -0.4271211
[3,] 0.9803156 -0.4271211 1.0000000
Now, let us take an Identity Matrix of dimensions, say 3×3, and find its Correlation Matrix.
example.R
</>
Copy
data <- c(1, 0, 0, 0, 1, 0, 0, 0, 1)
A <- matrix(data, nrow = 3, ncol = 3)
A_C <- cor(A)
print("Matrix A")
print(A)
print("Correlation Matrix of A")
print(A_C)
Output
[1] "Matrix A"
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[1] "Correlation Matrix of A"
[,1] [,2] [,3]
[1,] 1.0 -0.5 -0.5
[2,] -0.5 1.0 -0.5
[3,] -0.5 -0.5 1.0
Conclusion
In this R Tutorial, we learned how to Inverse a Matrix in R using solve() function, with the help of examples.