Create a Correlation Matrix From a Correlation Vector in R -
i want create correlation matrix given correlation vector, upper (or lower) triangular matrix of correlation matrix.
the goal transform vector
to correlation matrix 1s on diagonal.
do know if there method creating matrix given triangular above diagonal , set diagonal 1?
i don't know if there automatic way this, expanding on comment:
myvec <- c(-.55, -.48, .66, .47, -.38, -.46) mempty <- matrix(0, nrow = 4, ncol = 4) mindex <- matrix(1:16, nrow = 4, ncol = 4) mempty[mindex[upper.tri(mindex)]] <- myvec mempty[lower.tri(mempty)] <- t(mempty)[lower.tri(t(mempty))] diag(mempty) <- 1 mempty # [,1] [,2] [,3] [,4] # [1,] 1.00 -0.55 -0.48 0.47 # [2,] -0.55 1.00 0.66 -0.38 # [3,] -0.48 0.66 1.00 -0.46 # [4,] 0.47 -0.38 -0.46 1.00
here's hacked function. hope mathematics steps correct!
vec2symmat <- function(invec, diag = 1, byrow = true) { nrow <- ceiling(sqrt(2*length(invec))) if (!sqrt(length(invec)*2 + nrow) %% 1 == 0) { stop("invec wrong length create square symmetrical matrix") } mempty <- matrix(0, nrow = nrow, ncol = nrow) mindex <- matrix(sequence(nrow^2), nrow = nrow, ncol = nrow, byrow = byrow) if (istrue(byrow)) { mempty[mindex[lower.tri(mindex)]] <- invec mempty[lower.tri(mempty)] <- t(mempty)[lower.tri(t(mempty))] } else { mempty[mindex[upper.tri(mindex)]] <- invec mempty[lower.tri(mempty)] <- t(mempty)[lower.tri(t(mempty))] } diag(mempty) <- diag mempty }
here different value diagonal.
vec2symmat(1:3, diag = na) # [,1] [,2] [,3] # [1,] na 1 2 # [2,] 1 na 3 # [3,] 2 3 na
here's error message if try provide data can't create square matrix.
vec2symmat(1:4) # error in vec2symmat(1:4) : # invec wrong length create square symmetrical matrix
and, default settings.
vec2symmat(1:10) # [,1] [,2] [,3] [,4] [,5] # [1,] 1 1 2 3 4 # [2,] 1 1 5 6 7 # [3,] 2 5 1 8 9 # [4,] 3 6 8 1 10 # [5,] 4 7 9 10 1
Comments
Post a Comment