代码之家  ›  专栏  ›  技术社区  ›  J. Mini

如何通过一组列的函数打破排序数据中的联系?

  •  0
  • J. Mini  · 技术社区  · 5 年前

    考虑:

    > output<-cbind(matrix(sample(15,replace = TRUE),nrow=5,ncol=3),c(sample(5,replace = TRUE)+20),c(16,16,16,16,15))
    > output
         [,1] [,2] [,3] [,4] [,5]
    [1,]    5    8    3   25   16
    [2,]    7    3    6   23   16
    [3,]    7    9    7   21   16
    [4,]    2    8   13   23   16
    [5,]   11    1    3   22   15
    

    现在假设我想按第4列排序,按第5列打破联系。具有 order and a little help from Stack Overflow ,这不是什么挑战:

    > output[order(output[,4],output[,5]),]
         [,1] [,2] [,3] [,4] [,5]
    [1,]    7    9    7   21   16
    [2,]   11    1    3   22   15
    [3,]    7    3    6   23   16
    [4,]    2    8   13   23   16
    [5,]    5    8    3   25   16
    

    我的问题是在最后一个要求中:如果我想根据第1、2和3列中任何绑定行的条目对数据进行进一步排序,我该怎么做?例如,我如何实现排序: 按第4列的递增顺序排序。如果出现平局,请按第5列的升序排序。如果这其中也有一个并列关系,那么首先将所有列1、2和3中值最低的行放在第一位(即按最小值排序(第1列、第2列、第3列)) "?

    预期输出:在上述情况下,最终排序的第3行和第4行将被交换,因为min(2,8,13)小于min(7,3,6)。

    0 回复  |  直到 5 年前
        1
  •  1
  •   RyanFrost    5 年前

    这是在r底:

    output<-cbind(matrix(sample(15,replace = TRUE),nrow=5,ncol=3),
                  c(sample(5,replace = TRUE)+20),c(16,16,16,16,15))
    
    
    output[order(output[,4], output[,5], apply(output[, 1:3], 1, min)),]
    #>      [,1] [,2] [,3] [,4] [,5]
    #> [1,]   14   15    2   21   15
    #> [2,]    9    6    4   22   16
    #> [3,]   11   12   12   22   16
    #> [4,]   13    5    7   25   16
    #> [5,]   15   10    6   25   16
    

    我们使用 apply 找到前三列的行最小值向量,并将该向量作为第三个排序标准。

    如果您愿意使用数据帧,dplyr可以使其更易于阅读:

    library(dplyr)
    output %>%
      as.data.frame() %>% 
      arrange(V4, V5, pmin(V1, V2, V3))
    #>   V1 V2 V3 V4 V5
    #> 1 14 15  2 21 15
    #> 2  9  6  4 22 16
    #> 3 11 12 12 22 16
    #> 4 13  5  7 25 16
    #> 5 15 10  6 25 16
    

    于2020年6月6日由 reprex package (v0.3.0)

        2
  •  1
  •   akrun    5 年前

    在里面 base R ,我们能做到

    output1 <- as.data.frame(output)
    output[do.call(order, c(output1[4:5], list(do.call(pmin, output1[1:3])))),]
    #      [,1] [,2] [,3] [,4] [,5]
    #[1,]    7    9    7   21   16
    #[2,]   11    1    3   22   15
    #[3,]    2    8   13   23   16
    #[4,]    7    3    6   23   16
    #[5,]    5    8    3   25   16
    

    数据

    output <- cbind(c(5, 7, 7, 2, 11), c(8, 3, 9, 8, 1),
       c(3, 6, 7, 13, 3), c(25, 23, 21, 23, 22), c(16, 16, 16, 16, 15))