fastest way to get Min from every column in a matrix?

前端 未结 6 2088
执念已碎
执念已碎 2020-12-16 16:13

What is the fastest way to extract the min from each column in a matrix?


EDIT:

Moved all the benchmarks to the answer below.

Using

6条回答
  •  无人及你
    2020-12-16 16:53

    Below is a collection of the answers thus far. This will be updated as more answers are contributed.

    BENCHMARKS

      library(rbenchmark)
      library(matrixStats)  # for colMins
    
    
      list.of.tests <- list (
            ## Method 1: apply()  [original]
            apl =expression(apply(mat, 2, min, na.rm=T)),
    
            ## Method 2:  matrixStats::colMins [contributed by @Ben Bolker ]
            cmin = expression(colMins(mat)),
    
            ## Method 3: lapply() + split()  [contributed by @DWin ]
            lapl = expression(lapply( split(mat, rep(1:dim(mat)[1], each=dim(mat)[2])), min)),
    
            ## Method 4: pmin() / pmin.int()  [contributed by @flodel ]
            pmn = expression(do.call(pmin, lapply(1:nrow(mat), function(i)mat[i,]))),
            pmn.int = expression(do.call(pmin.int, lapply(1:nrow(mat), function(i)mat[i,]))) #,
    
            ## Method 5: ????
            #  e5 = expression(  ???  ),
            )  
    
    
      (times <- 
            lapply(matrix.inputs, function(mat)
                do.call(benchmark, args=c(list.of.tests, replications=500, order="relative"))[, c("test", "elapsed", "relative")]
      ))
    
    
    
      ############################# 
      #$         RESULTS         $#
      #$_________________________$#
      #############################
    
      # $`Square Matrix`
      #      test elapsed relative
      # 5 pmn.int   2.842    1.000
      # 4     pmn   3.622    1.274
      # 1     apl   3.670    1.291
      # 2    cmin   5.826    2.050
      # 3    lapl  41.817   14.714  
    
      # $`Tall Matrix`
      #      test elapsed relative
      # 1     apl   2.622    1.000
      # 2    cmin   5.561    2.121
      # 5 pmn.int  11.264    4.296
      # 4     pmn  18.142    6.919
      # 3    lapl  48.637   18.550  
    
      # $`Wide-short Matrix`
      #      test elapsed relative
      # 5 pmn.int   2.909    1.000
      # 4     pmn   3.018    1.037
      # 2    cmin   6.361    2.187
      # 1     apl  15.765    5.419
      # 3    lapl  41.479   14.259  
    
      # $`Wide-tall Matrix`
      #      test elapsed relative
      # 5 pmn.int  20.917    1.000
      # 4     pmn  26.188    1.252
      # 1     apl  38.635    1.847
      # 2    cmin  64.557    3.086
      # 3    lapl 434.761   20.785  
    
      # $`Tiny Sq Matrix`
      #      test elapsed relative
      # 5 pmn.int   0.112    1.000
      # 2    cmin   0.149    1.330
      # 4     pmn   0.174    1.554
      # 1     apl   0.180    1.607
      # 3    lapl   0.509    4.545
    

提交回复
热议问题