编辑:一个相关的问题是How to move larger values close to matrix diagonal in a correlation matrix这个问题是关于在R
中实现相同的问题给定矩阵(或R中的表格)
m <- matrix(c(5,25,8,4,2,10,20,3,1),ncol=3,byrow=TRUE)
colnames(m) <- c("L","M","H")
rownames(m) <- c("A","B","C")
tax <- as.table(m)
tax
L M H
A 5 25 8
B 4 2 10
C 20 3 1
我想重新排列矩阵,使对角线元素最大。
H L M
B 10 4 2
C 1 20 3
A 8 5 25
R中有没有易于使用的功能?
答案 0 :(得分:2)
matrix.sort <- function(matrix) {
if (nrow(matrix) != ncol(matrix)) stop("Not diagonal")
if(is.null(rownames(matrix))) rownames(matrix) <- 1:nrow(matrix)
row.max <- apply(matrix,1,which.max)
if(all(table(row.max) != 1)) stop("Ties cannot be resolved")
matrix[names(sort(row.max)),]
}
答案 1 :(得分:0)
我不认为Rohit Arora的解决方案完全可以满足您的要求,因为它将由上一行的最大值来主导。结果,实际上并不是在优化意义上最大化对角线。
我在其他地方找到了类似问题的答案,我认为这可能有用:
The application assignment to users
pMatrix.min <- function(A, B) {
#finds the permutation P of A such that ||PA - B|| is minimum in Frobenius norm
# Uses the linear-sum assignment problem (LSAP) solver in the "clue" package
# Returns P%*%A and the permutation vector `pvec' such that
# A[pvec, ] is the permutation of A closest to B
n <- nrow(A)
D <- matrix(NA, n, n)
for (i in 1:n) {
for (j in 1:n) {
D[j, i] <- (sum((B[j, ] - A[i, ])^2))
}
}
vec <- c(solve_LSAP(D))
list(A=A[vec,], pvec=vec)
}
require(clue) # need this package to solve the LSAP
#An example
A <- matrix(sample(1:25, size=25, rep=FALSE), 5, 5)
B <- diag(1, nrow(A)) # this choice of B maximizes the trace of permuted A
X <- pMatrix.min(A,B)
A # original square matrix
X$A # permuted A such that its trace is maximum among all permutations
它使用匈牙利方法来优化矩阵A到目标矩阵B的重新排序。
NB这是我的第一篇文章,所以我不敢对上一个答案发表评论,但我希望这会有所帮助!