* This tutorial is a continuation of making a covariance matrix in R. These tutorials walk you through the matrix algebra necessary to create the matrices, so you can better understand what is going on underneath the hood in R. There are built-in functions within R that make this process much quicker and easier. *

The correlation matrix is is rather popular for exploratory data analysis, because it can quickly show you the correlations between variables in your data set. From a practical application standpoint, this entire post is unnecessary, because I’m going to show how to derive this using matrix algebra in R.

First, the starting point will be the covariance matrix that was computed from the last post.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#create vectors -- these will be our columns a <- c(1,2,3,4,5,6) b <- c(2,3,5,6,1,9) c <- c(3,5,5,5,10,8) d <- c(10,20,30,40,50,55) e <- c(7,8,9,4,6,10) #create matrix from vectors M <- cbind(a,b,c,d,e) k <- ncol(M) #number of variables n <- nrow(M) #number of subjects #create means for each column M_mean <- matrix(data=1, nrow=n) %*% cbind(mean(a),mean(b),mean(c),mean(d),mean(e)) #creates a difference matrix D <- M - M_mean #creates the covariance matrix C <- k^-1 * t(D) %*% D |

This matrix has all the information that’s needed to get the correlations for all the variables and create a correlation matrix [V — variance, C — Covariance]. Correlation, we are using the Pearson version of correlation, is calculated using the covariance between two vectors and their standard deviations [*s*, square root of the variance]:

The trick will be using matrix algebra to easily carry out these calculations. The variance components are all on the diagonal of the covariance matrix, so in matrix algebra notation we want to use this:

Since R doesn’t quite work the same way as matrix algebra notation, the diag() function creates a vector from a matrix and a matrix from a vector, so it’s used twice to create the diagonal variance matrix. Once to get a vector of the variances, and a second time to turn that vector into the above diagonal matrix. Since the standard deviations are needed, the square root is taken. Also the variances are inverted to facilitate division.

1 2 |
#pulls out the standard deviations from the covariance matrix S <- diag(diag(C)^(-1/2)) |

After getting the diagonal matrix, basic matrix multiplication is used to get the all the terms in the covariance to reflect the basic correlation formula from above.

1 2 |
#constructs the correlation matrix S %*% C %*% S |

And the correlation matrix is symbolically represented as:

The diagonal where the variances where in the covariance matrix are now 1, since a variable’s correlation with itself is always 1.