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:
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
CodePudding user response:
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
CodePudding user response:
You can use the diag
function. For a matrix m
, the following...
diag(m) <- pmax(1, diag(m))
will set any values on the diagonal to a minimum of 1.