Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中列数可变的排序矩阵_R_Sorting_Matrix - Fatal编程技术网

R中列数可变的排序矩阵

R中列数可变的排序矩阵,r,sorting,matrix,R,Sorting,Matrix,我想根据列“summ”按升序对矩阵MM进行排序,然后对列1按降序排序,直到列“summ”之前。因此,如果n=4,那么我需要根据列“summ”按升序对MM进行排序,然后根据列1到4的降序对MM进行排序。我的代码是: n <- 4 M <- matrix(NA_integer_, nrow=2^n-1, ncol=n) M <- as.matrix(M) for (i in 1:(2^n-1)) M[i, ] <- as.integer(intToBits(i)[1:n

我想根据列“summ”按升序对矩阵MM进行排序,然后对列1按降序排序,直到列“summ”之前。因此,如果n=4,那么我需要根据列“summ”按升序对MM进行排序,然后根据列1到4的降序对MM进行排序。我的代码是:

n <- 4
M <- matrix(NA_integer_, nrow=2^n-1, ncol=n)
M <- as.matrix(M)
for (i in 1:(2^n-1))
   M[i, ] <- as.integer(intToBits(i)[1:n])
MM <- data.frame(M[-1,])
MM <- cbind(M,apply(M, 1, sum))
dimnames(MM)[[2]] <- c(paste("item",1:n,sep=""), "summ")

n您可以尝试按照以下方式使用自定义函数:

CustomOrder <- function(inTable) {
  n <- ncol(inTable)
  Order <- do.call(order, c(data.frame(inTable[, n], inTable[, 1:(n-1)] * -1)))
  inTable[Order, ]
}
CustomOrder <- function(inTable) {
  n <- ncol(inTable)
  Order <- do.call(order, c(data.frame(inTable[, n], inTable[, 1:(n-1)] * -1)))
  inTable[Order, ]
}
CustomOrder(MM)
#       item1 item2 item3 item4 summ
#  [1,]     1     0     0     0    1
#  [2,]     0     1     0     0    1
#  [3,]     0     0     1     0    1
#  [4,]     0     0     0     1    1
#  [5,]     1     1     0     0    2
#  [6,]     1     0     1     0    2
#  [7,]     1     0     0     1    2
#  [8,]     0     1     1     0    2
#  [9,]     0     1     0     1    2
# [10,]     0     0     1     1    2
# [11,]     1     1     1     0    3
# [12,]     1     1     0     1    3
# [13,]     1     0     1     1    3
# [14,]     0     1     1     1    3
# [15,]     1     1     1     1    4