I think you might need to get the indices with which
and then swap the rows and columns. Try this.
k <- which(lower.tri(my.matrix), arr.ind=TRUE)
my.matrix[k[,c(2,1)]] <- my.matrix[k]
Question
Is there an easy way to convert a correlation-covariance matrix into a variance-covariance matrix? I always use nested for-loops
as below, but I keep thinking there is probably a built-in function in base R
.
my.matrix <- matrix(c(0.64901, 0.76519, -0.63620, -0.01923,
0.02114, 0.00118, -0.43198, 0.02480,
-0.21811, -0.00630, 0.18109, 0.05964,
-0.00710, 0.00039, 0.01162, 0.20972), nrow=4, byrow=TRUE)
new.matrix <- my.matrix
for(i in 1:nrow(my.matrix)) {
for(j in 1:ncol(my.matrix)) {
new.matrix[i,j] = ifelse(i<j, my.matrix[j,i], new.matrix[i,j])
}
}
new.matrix
# [,1] [,2] [,3] [,4]
# [1,] 0.64901 0.02114 -0.21811 -0.00710
# [2,] 0.02114 0.00118 -0.00630 0.00039
# [3,] -0.21811 -0.00630 0.18109 0.01162
# [4,] -0.00710 0.00039 0.01162 0.20972
I am aware of the lower.tri
and upper.tri
functions, but cannot seem to accomplish the task with a combination of them and t()
.
Solution
I think you might need to get the indices with which
and then swap the rows and columns. Try this.
k <- which(lower.tri(my.matrix), arr.ind=TRUE)
my.matrix[k[,c(2,1)]] <- my.matrix[k]