Select a subset of combinations

前端 未结 2 907
孤街浪徒
孤街浪徒 2021-01-20 14:53

Suppose that I have a 20 X 5 matrix, I would like to select subsets of the matrix and do some computation with them. Further suppose that each sub-matrix is 7 X 5. I could o

2条回答
  •  自闭症患者
    2021-01-20 15:54

    Your approach:

    op <- function(){
        ncomb <- combn(20, 7)
        ncombsub <- ncomb[, sample(choose(20,7), 5000)]
        return(ncombsub)
    }
    

    A different strategy that simply samples seven rows from the original matrix 5000 times (replacing any duplicate samples with a new sample until 5000 unique row combinations are found):

    me <- function(){
      rowsample <- replicate(5000,sort(sample(1:20,7,FALSE)),simplify=FALSE)
      while(length(unique(rowsample))<5000){
         rowsample <- unique(rowsample)
         rowsample <- c(rowsample,
                        replicate(5000-length(rowsample),
                                  sort(sample(1:20,7,FALSE)),simplify=FALSE))
      }
      return(do.call(cbind,rowsample))
    }
    

    This should be more efficient because it prevents you from having to calculate all of the combinations first, which will get costly as the matrix gets larger.

    And yet, some benchmarking reveals that is not the case. At least on this matrix:

    library(microbenchmark)
    microbenchmark(op(),me())
    
    Unit: milliseconds
     expr      min       lq   median      uq      max neval
     op() 184.5998 201.9861 206.3408 241.430 299.9245   100
     me() 411.7213 422.9740 429.4767 474.047 490.3177   100
    

提交回复
热议问题