【问题标题】:Sort matrix with variable number of columns in R在R中对具有可变列数的矩阵进行排序
【发布时间】:2014-03-01 16:24:42
【问题描述】:

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

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 的通用解决方案。

MMM <- MM[order(MM[,n+1],-MM[,1],-MM[,2],-MM[,3],-MM[,4]),]
      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

感谢您的帮助!

【问题讨论】:

    标签: r sorting matrix


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 2012-12-30
      • 1970-01-01
      相关资源
      最近更新 更多