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

前端 未结 6 2080
执念已碎
执念已碎 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 17:13

    The sos package is great for answering these sorts of questions.

    library("sos")
    findFn("colMins")
    library("matrixStats")
    ?colMins
    

    http://finzi.psych.upenn.edu/R/library/matrixStats/html/rowRanges.html

    Oddly enough, for the one example I tried colMins was slower. Perhaps someone can point out what's funny about my example?

    set.seed(101); z <- matrix(runif(1e6),nrow=1000)
    library(rbenchmark)
    benchmark(colMins(z),apply(z,2,min))
    ##               test replications elapsed relative user.self sys.self
    ## 2 apply(z, 2, min)          100  14.290     1.00     7.216    7.057
    ## 1       colMins(z)          100  25.585     1.79    15.509    9.852
    

提交回复
热议问题