I am trying to make a symmetric matrix using R. I already have a matrix. My matrix is very big so below is a simple example.
EX.
1 2 3
4 5 6
7 8 9
I need to make them like this.
1 2+4 3+7
4+2 5 6+8
7+3 8+6 9
//So I tried this. // mat is the matrix I am using.
lowervector <- square_07[lower.tri(square_07, diag = FALSE)]
uppervector <- square_07[upper.tri(square_07, diag = FALSE)]
lowermat <- square_07
uppermat <- square_07
lowermat[lower.tri(lowermat, diag = FALSE)] <- t(square_07)[lower.tri(square_07, diag = FALSE)]
uppermat[upper.tri(uppermat, diag = FALSE)] <- t(square_07)[upper.tri(square_07, diag = FALSE)]
When I execute the last 2 lines, an error occurs;
Subscript 'upper.tri(uppermat, diag = FALSE)' is a matrix, the data 't[upper.tri(square_07, diag = FALSE)]' must have size 1.
You should know. The upper matrix is just an example. My actual matrix is much more bigger. It is a 248*248 matrix.
How can I solve this problem?
You can try this -
mat[upper.tri(mat)] <- mat[upper.tri(mat)] + mat[lower.tri(mat)]
mat[lower.tri(mat)] <- mat[upper.tri(mat)]
mat
# [,1] [,2] [,3]
#[1,] 1 6 10
#[2,] 6 5 14
#[3,] 10 14 9
data
mat <- structure(c(1L, 4L, 7L, 2L, 5L, 8L, 3L, 6L, 9L), .Dim = c(3L, 3L))
mat
# [,1] [,2] [,3]
#[1,] 1 2 3
#[2,] 4 5 6
#[3,] 7 8 9