jeromyanglim / learning_r

assorted notes to self while learning R
1 stars 0 forks source link

How to create correlation matrix from vector of correlations using R? #8

Closed jeromyanglim closed 12 years ago

jeromyanglim commented 12 years ago

I sometimes need to create a correlation matrix from a vector of correlations where the vector is just the lower or upper diagonal correlations. Thus the function needs to insert the elements of the vector in appropriate cells, create a symmetric matrix and add the 1s to the diagonal.

How can this be done in R?

jeromyanglim commented 12 years ago

I wrote the following function

vector2rmatrix <- function(x) {
    # x: vector of correlations representing either
    # (a) upper off-diagonal elements of matrix arranged row-wise, or equivalently
    # (b) lower off-diagnoal elements of matrix arrange column-wise.
    V <- length(x)
    p <- (1 + sqrt(1 + 8 * V))/2
    if (p %% 1 != 0) stop('input vector has invalid length')
    r_matrix <- diag(rep(1, p))
    r_matrix[lower.tri(r_matrix)] <- x
    r_matrix[upper.tri(r_matrix)] <- t(r_matrix)[upper.tri(r_matrix)]
    r_matrix
}

Ben Bolker also sets out a similar approach on R Help: https://stat.ethz.ch/pipermail/r-help/2005-December/083887.html