In terms of the application of clustering algorithm, after I got the contingency table of the counts at each combination of actual class and predicted class, for example,
1 2 3
A 2 3 15
B 20 1 4
C 0 32 1
How could I write a function to get the confusion matrix that maximizes the diagonal by changing the order of columns? Thanks!
1 2 3
A 15 2 3
B 4 20 1
C 1 0 32
We could use max.col
to get the column index of the max value per row, and use that for rearranging the columns
m2 <- m1[,max.col(m1, 'first')]
colnames(m2) <- seq_len(ncol(m2))
m2
# 1 2 3
#A 15 2 3
#B 4 20 1
#C 1 0 32
m1 <- structure(c(2L, 20L, 0L, 3L, 1L, 32L, 15L, 4L, 1L), .Dim = c(3L,
3L), .Dimnames = list(c("A", "B", "C"), c("1", "2", "3")))