Home > Back-end >  Make the matrix symmetric
Make the matrix symmetric

Time:11-23

I have a matrix:

contingency.table.1 <- structure(c(40, 5, 1, 0, 24, 8, 0, 1, 2, 1, 1, 0, 0, 1, 0, 1), .Dim = c(4L, 
4L), .Dimnames = list(col1 = c("0", "1", "2", "3"), col2 = c("0", 
"1", "2", "3")), class = "table")

Then, if I meet 0 on the diagonal of the matrix, then I replace it with 1

contingency.table.1[row(contingency.table.1) == 
                                              col(contingency.table.1) & contingency.table.1 == 0] <- 1

I would like to get a matrix, if there are 0 on the symmetric position, then replace them both with 1

What I want to get:

contingency.table.1 <- structure(c(40, 5, 1, 1, 24, 8, 0, 1, 2, 1, 1, 0, 1, 1, 0, 1), .Dim = c(4L, 
4L), .Dimnames = list(col1 = c("0", "1", "2", "3"), col2 = c("0", 
"1", "2", "3")), class = "table")

if both zeros are in symmetrical positions, then replace them with 1

CodePudding user response:

Using a for loop.

rp <- \(m) {
  stopifnot(diff(dim(m)) == 0L)  ## symmetricity check
  for (i in seq_len(ncol(m)) - 1L) {
    c1 <- n - i
    c2 <- i   1L
    if (all(c(m[c1, c2], m[c2, c1]) == 0))
      m[c1, c2] <- m[c2, c1] <- 1
  }
  m
}

rp(contingency.table.1)
#     col2
# col1  0  1  2  3
#    0 40 24  2  1
#    1  5  8  1  1
#    2  1  0  1  0
#    3  1  1  0  1

CodePudding user response:

Just test where the matrix equals the transposed matrix, and where it equals zero

m <- contingency.table.1  
contingency.table.1[m == t(m) & m == 0] <- 1

Result

contingency.table.1
#>     col2
#> col1  0  1  2  3
#>    0 40 24  2  1
#>    1  5  8  1  1
#>    2  1  0  1  1
#>    3  1  1  1  1

Created on 2022-11-23 with reprex v2.0.2

  • Related