R 如何在给定任意列数的情况下对矩阵的行进行有效排序?
让我们只创建一个三项的假测试(n=3)。每个问题的答案可以是对的(1),也可以是错的(0)。测试结果只有八种可能,即所有1、所有0以及它们之间的一些组合。以下代码可用于模拟此场景:R 如何在给定任意列数的情况下对矩阵的行进行有效排序?,r,matrix,rows,R,Matrix,Rows,让我们只创建一个三项的假测试(n=3)。每个问题的答案可以是对的(1),也可以是错的(0)。测试结果只有八种可能,即所有1、所有0以及它们之间的一些组合。以下代码可用于模拟此场景: n=3; m=0 while(m!=2^n) { tmat = t(sapply(1:(10*2^n), function(x) sample(c(0,1), n, replace=T))) pats = apply(tmat, 1, paste, collapse="/") pats = unique(pat
n=3; m=0
while(m!=2^n) {
tmat = t(sapply(1:(10*2^n), function(x) sample(c(0,1), n, replace=T)))
pats = apply(tmat, 1, paste, collapse="/")
pats = unique(pats)
m = length(pats)
}
xmat = matrix(as.numeric(unlist(strsplit(pats, "/"))), ncol=n, nrow=m, byrow=T)
但是,现在我需要对xmat的行进行排序,结果应该如下所示:
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 1 0 0 1
[3,] 0 1 0 1
[4,] 0 0 1 1
[5,] 1 1 0 2
[6,] 1 0 1 2
[7,] 0 1 1 2
[8,] 1 1 1 3
xmat = xmat[order(xmat[,n+1], xmat[,n], xmat[,n-1]), ... , xmat[,2])
我使用此代码获得上述结果:
# create the fourth column which is the total score
xmat = cbind(xmat, rowSums(xmat))
# order by the 4th column, then 3rd column, then 2nd column.
xmat = xmat[order(xmat[,4], xmat[,3], xmat[,2]),]
我的问题是,将来我将有任意数量的列n(在本例中,n=3)。我无法手动将n-1项放入代码中,以便对矩阵进行如下排序:
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 1 0 0 1
[3,] 0 1 0 1
[4,] 0 0 1 1
[5,] 1 1 0 2
[6,] 1 0 1 2
[7,] 0 1 1 2
[8,] 1 1 1 3
xmat = xmat[order(xmat[,n+1], xmat[,n], xmat[,n-1]), ... , xmat[,2])
有没有简单的方法来完成最后一步
提前谢谢你 我认为应该这样做:
xmat[do.call(order, rev(split(xmat, col(xmat)))), ]
其中:
split(xmat,col(xmat)
将矩阵拆分为列列表rev
对列表重新排序(最后一列在前)do.call
调用列表中的order
我认为这应该做到:
xmat[do.call(order, rev(split(xmat, col(xmat)))), ]
其中:
split(xmat,col(xmat)
将矩阵拆分为列列表rev
对列表重新排序(最后一列在前)do.call
调用列表中的order