R中循环的优化

时间:2018-11-26 09:53:27

标签: r

鉴于r是一个包含lm列的矩阵,我想最优化以下代码。有什么想法吗?

    set.seed(123456)
    system.time(expr = {
      r = matrix(rnorm(15 * 1500), ncol = 15)
      s = 0
      lm = ncol(r)
##################
      for (j in 1:lm) {
        cm  = combn(lm, j)
        for (i in 1:ncol(cm)) {
          val = apply(r, 1, function(x) {
            prod(x[cm[, i]])
          })
          s = s + (-1) ^ (j + 1) * val
        }
      }
    }
###############
)

  user  system elapsed 
 110.56    0.07  111.37 

1 个答案:

答案 0 :(得分:2)

快65倍

    library(Rfast)
    set.seed(123456)
    system.time(expr = {
      r = matrix(rnorm(15 * 1500), ncol = 15)
      s = 0
      lm = ncol(r)
      for (j in 1:lm) {
        val = sapply(
          X = combn(lm, j, simplify = FALSE),
          FUN = function(i) {
            val = (-1) ^ (j + 1)  * rowprods(r[, i, drop = FALSE])
          }
        )
        s = s + rowSums(val)
      }
    })

    user  system elapsed 
   1.70    0.09    1.84