简体   繁体   中英

how to reorder the contingency table to form a confusion matrix in R

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

data

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")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM