如何在较大的数据集上迭代执行组合?

问题描述 投票:1回答:1

背景 - 我想尝试并详尽地搜索一次10个10行的所有可能组合的集合。为了迭代得到这个,我使用以下代码

`
## Function definition
gen.next.cbn <- function(cbn, n){
  ## Generates the combination that follows the one provided as input
  cbn.bin      <- rep(0, n)
  cbn.bin[cbn] <- 1
  if (tail(cbn.bin, 1) == 0){
    ind <- tail(which(cbn.bin == 1), 1)
    cbn.bin[c(ind, ind+1)] <- c(0, 1)
  }else{
    ind <- 1 + tail(which(diff(cbn.bin) == -1), 1)
    nb  <- sum(cbn.bin[-c(1:ind)] == 1)
    cbn.bin[c(ind-1, (n-nb+1):n)] <- 0
    cbn.bin[ind:(ind+nb)]         <- 1
  }
  cbn <- which(cbn.bin == 1)
}

## Example parameters
n   <- 40
k   <- 10

## Iteration example
for (i in 1:choose(n, k)){
  if (i == 1){
    cbn <- 1:k
  }else{
    cbn <- gen.next.cbn(cbn, n)

  }
  print(cbn)


}


`

当我超过40行时,我收到错误“无法分配大小为n GB的向量”。

理想的解决方案:a)如果可以转储组合,并且可以在循环中的每次运行后迭代地刷新内存(我可以检查其他条件)b)如果组合可以转储到csv文件,这样它就不会导致记忆猪。

感谢您的支持。

r dataset combinations combn
1个回答
1
投票

正如我在评论中所说,iterpc是完成这项任务的方法。首先需要通过iterpc函数初始化迭代器。接下来,我们可以通过n生成下一个getnext组合。在此之后,我们只需将结果附加到csv(或您喜欢的任何文件类型)。

getComboChunks <- function(n, k, chunkSize, totalCombos, myFile) {
    myIter <- iterpc(n, k)

    ## initialized myFile
    myCombs <- getnext(myIter, chunkSize)
    write.table(myCombs, file = myFile, sep = ",", col.names = FALSE)

    maxIteration <- (totalCombos - chunkSize) %/% chunkSize

    for (i in 1:maxIteration) {
        ## get the next "chunkSize" of combinations
        myCombs <- getnext(myIter, chunkSize)

        ## append the above combinations to your file
        write.table(myCombs, file = myFile, sep = ",",
                    col.names = FALSE , append = TRUE)
    }
}

例如,getComboChunks(250, 10, 100, 1000, "myCombos.csv")将一次向文件myCombos.csv 100组合写出250个选择10的组合。以块的形式执行此操作将比一次更有效。

这个库是用C/C++编写的,所以它应该是相当有效的,但正如@Florian在评论中指出的那样,它不会很快产生所有的gmp::chooseZ(250, 10) = Big Integer ('bigz') : [1] 219005316087032475组合。我没有测试过它,但是如果你满足于200选择5,我认为你将能够在一天之内生产它(结果只有超过25亿)。

© www.soinside.com 2019 - 2024. All rights reserved.