Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get a matrix with units at the intersection

my data:

data = structure(list(st1 = c(7L, 7L, 6L, 7L, 5L, 6L, 7L, 7L, 8L, 8L, 
3L, 9L, 5L, 3L, 4L, 4L, 6L, 4L, 5L, 3L, 6L), st2 = c(1L, 0L, 
0L, 0L, 0L, 0L, 0L, 1L, 0L, 2L, 0L, 1L, 0L, 0L, 3L, 0L, 0L, 0L, 
0L, 0L, 0L), group = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA, 
-21L))

I create a matrix and build it up to a square one using 1

contingency.table.1 = data.frame(data[[1]],data[[2]])
contingency.table.1 = table(contingency.table.1[c(1,2)])
contingency.table.1 <- make_symmetric_matrix(contingency.table.1)

make_symmetric_matrix <- function(m) {
    nr <- nrow(m)
    nc <- ncol(m)
    if(nc > nr) {
        m <- rbind(m, matrix(1, nrow = nc - nr, nc = nc))
    } else if(nr > nc) {
        m <- cbind(m, matrix(1, nrow = nr, nc = nr - nc))
    }
    m
}

And I get the following matrix:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  0 1 2 3      
3 3 0 0 0 1 1 1
4 2 0 0 1 1 1 1
5 3 0 0 0 1 1 1
6 4 0 0 0 1 1 1
7 3 2 0 0 1 1 1
8 1 0 1 0 1 1 1
9 0 1 0 0 1 1 1

I would like to get the following matrix

 0 1 2 3      
3 3 0 0 0 1 1 1
4 2 1 0 1 1 1 1
5 3 0 1 0 1 1 1
6 4 0 0 1 1 1 1
7 3 2 0 0 1 1 1
8 1 0 1 0 1 1 1
9 0 1 0 0 1 1 1

if there is 0 on the diagonal, then replace it with 1

>Solution :

We can create a condition with row/col and assign the values where they are 0 to 1

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

-output

> contingency.table.1
  0 1 2 3      
3 3 0 0 0 1 1 1
4 2 1 0 1 1 1 1
5 3 0 1 0 1 1 1
6 4 0 0 1 1 1 1
7 3 2 0 0 1 1 1
8 1 0 1 0 1 1 1
9 0 1 0 0 1 1 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading