Row-wise variance of a matrix in R

前端 未结 2 620
礼貌的吻别
礼貌的吻别 2020-11-30 09:11

I\'d like to compute the variance for each row in a matrix. For the following matrix A

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    5    6            


        
2条回答
  •  误落风尘
    2020-11-30 09:40

    This is one of the main reasons why apply() is useful. It is meant to operate on the margins of an array or matrix.

    set.seed(100)
    m <- matrix(sample(1e5L), 1e4L)
    library(microbenchmark)
    microbenchmark(apply(m, 1, var))
    # Unit: milliseconds
    #              expr      min       lq   median       uq      max neval
    #  apply(m, 1, var) 270.3746 283.9009 292.2933 298.1297 343.9531   100 
    

    Is 300 milliseconds too long to make 10,000 calculations?

提交回复
热议问题