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

前端 未结 6 2078
执念已碎
执念已碎 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

    Here is one that is faster on square and wide matrices. It uses pmin on the rows of the matrix. (If you know a faster way of splitting the matrix into its rows, please feel free to edit)

    do.call(pmin, lapply(1:nrow(mat), function(i)mat[i,]))
    

    Using the same benchmark as @RicardoSaporta:

    $`Square Matrix`
              test elapsed relative
    3 pmin.on.rows   1.370    1.000
    1          apl   1.455    1.062
    2         cmin   2.075    1.515
    
    $`Wide Matrix`
          test elapsed relative
    3 pmin.on.rows   0.926    1.000
    2         cmin   2.302    2.486
    1          apl   5.058    5.462
    
    $`Tall Matrix`
              test elapsed relative
    1          apl   1.175    1.000
    2         cmin   2.126    1.809
    3 pmin.on.rows   5.813    4.947
    

提交回复
热议问题