Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

r - Permute columns of a square 2-way contingency table (matrix) to maximize its diagonal

After doing clustering, the labels found are meaningless. One can calculate a contingency table to see which labels are most related to the original classes if the ground-truth is available.

I want to automatically permute columns of a contingency table to maximize its diagonal. For example:

# Ground-truth labels
c1 = c(1,1,1,1,1,2,2,2,3,3,3,3,3,3,3)
# Labels found
c2 = c(3,3,3,3,1,1,1,1,2,2,2,3,2,2,1)
# Labels found but renamed correctly
c3 = c(1,1,1,1,2,2,2,2,3,3,3,1,3,3,2)

# Current output
tab1 <- table(c1,c2)
#   c2
#c1  1 2 3
#  1 1 0 4
#  2 3 0 0
#  3 1 5 1

# Desired output
tab2 <- table(c1,c3)
#   c3
#c1  1 2 3
#  1 4 1 0
#  2 0 3 0
#  3 1 1 5

In reality, c3 is not available. Is there an easy way to obtain c3, tab2 from c2, tab1?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
c1 <- c(1,1,1,1,1,2,2,2,3,3,3,3,3,3,3)
c2 <- c(3,3,3,3,1,1,1,1,2,2,2,3,2,2,1)

## table works with factor variables internally
c1 <- as.factor(c1)
c2 <- as.factor(c2)

tab1 <- table(c1, c2)
#       c2
#    c1  1 2 3
#      1 1 0 4
#      2 3 0 0
#      3 1 5 1

Your question is essentially: how to re-level c2 so that the maximum value on a row sits on the main diagonal. In terms of matrix operation, this is a column permutation.

## find column permutation index
## this can potentially be buggy if there are multiple maxima on a row
## because `sig` may then not be a permutation index vector
## A simple example is:
## tab1 <- matrix(5, 3, 3); max.col(tab1, "first")
sig <- max.col(tab1, "first")
#[1] 3 1 2

## re-level `c2` (create `c3`)
c3 <- factor(c2, levels = levels(c2)[sig])

## create new contingency table
table(c1, c3)
#   c3
#c1  3 1 2
#  1 4 1 0
#  2 0 3 0
#  3 1 1 5

## if creation of `c3` is not necessary, just do
tab1[, sig]
#   c3
#c1  3 1 2
#  1 4 1 0
#  2 0 3 0
#  3 1 1 5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...