1

My question is very similar to: Reading a symmetric matrix from file that omits upper triangular part

With the main difference being that my pairwise matrix is missing the diagonal, which I would like it to set to 0.

So, if I have to read a matrix that looks like this:

> x
   1    2     3     4     5    6
1 NA 0.043 0.080 0.106 0.032 0.058
2 NA    NA 0.078 0.112 0.035 0.071
3 NA    NA    NA 0.100 0.068 0.100
4 NA    NA    NA    NA 0.093 0.129
5 NA    NA    NA    NA    NA 0.059

How can I add the "zeros diagonal" and then convert it to a symmetric matrix?

EDIT: this is how the desired output should look:

> y
    1        2         3        4      5       6
1   0.000   0.043   0.080   0.106   0.032   0.058
2   0.043   0.000   0.078   0.112   0.035   0.071
3   0.080   0.078   0.000   0.100   0.068   0.100
4   0.106   0.112   0.100   0.000   0.093   0.129
5   0.032   0.035   0.068   0.093   0.000   0.059
6   0.058   0.071   0.100   0.129   0.059   0.000

I'm sure it is very simple, but can't figure it out. Thanks in advance.

Data for example:

x<-structure(c(NA, NA, NA, NA, NA, 0.043, NA, NA, NA, NA, 0.08, 
0.078, NA, NA, NA, 0.106, 0.112, 0.1, NA, NA, 0.032, 0.035, 0.068, 
0.093, NA, 0.058, 0.071, 0.1, 0.129, 0.059), .Dim = 5:6, .Dimnames = list(
    c("1", "2", "3", "4", "5"), c("1", "2", "3", "4", "5", "6"
    )))
Community
  • 1
  • 1
A.Mstt
  • 301
  • 1
  • 3
  • 15
  • Since you have a 5x6 matrix, (which can't be symmetric) can you please show the expected result? – Roland Sep 18 '14 at 11:12
  • Yes, sorry, that's part of the issue of how the inputfile comes. Just a sec and I would edit the question. – A.Mstt Sep 18 '14 at 11:13

2 Answers2

3

First, you'd have to add an additional row of NAs to your matrix (since right now it is 5 by 6):

x <- rbind(x, "6"=NA)

Then you can turn the entire lower half (including the diagonals) to 0s, then add it to its own transpose:

x[!upper.tri(x)] <- 0
result <- x + t(x)

(Note that in your case, x[is.na(x)] <- 0 would also work).

David Robinson
  • 77,383
  • 16
  • 167
  • 187
0

Also:

nm1 <- unique(unlist(dimnames(x)))
x1 <- matrix(NA, ncol=length(nm1), nrow=length(nm1), dimnames=list(nm1, nm1))
x1[match(rownames(x), nm1), match(colnames(x), nm1)] <- x

library(Matrix) 
x2 <- forceSymmetric(x1)
diag(x2) <- 0
 x2
 #6 x 6 Matrix of class "dsyMatrix"
 #     1     2     3     4     5     6
 #1 0.000 0.043 0.080 0.106 0.032 0.058
 #2 0.043 0.000 0.078 0.112 0.035 0.071
 #3 0.080 0.078 0.000 0.100 0.068 0.100
 #4 0.106 0.112 0.100 0.000 0.093 0.129
 #5 0.032 0.035 0.068 0.093 0.000 0.059
 #6 0.058 0.071 0.100 0.129 0.059 0.000
akrun
  • 874,273
  • 37
  • 540
  • 662