排列方形2向列联表(矩阵)的列以最大化其对角线

时间:2018-09-27 14:23:00

标签: r matrix cluster-analysis crosstab contingency

进行聚类后,找到的标签毫无意义。可以计算一个列联表,以查看哪些标签与原始类别最相关。

我想自动排列列联表的列以最大化其对角线。例如:

# 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

实际上,c3不可用。是否有一种简单的方法可以从c3tab2获取c2tab1

1 个答案:

答案 0 :(得分:0)

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

本质上,您的问题是:如何重新调整c2的级别,以使一行的最大值位于主对角线上。在矩阵运算方面,这是列排列。

## 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