r - 使用combn()和bigmemory包生成一个非常大的字符串组合矩阵

标签 r combinatorics bigdata

我有一个由 1,344 个唯一字符串组成的向量 x。我想生成一个矩阵,为我提供所有可能的三个值组(无论顺序如何),并将其导出到 csv。

我在 64 位 Ubuntu 的 m1.large 实例上的 EC2 上运行 R。使用combn(x, 3)时出现内存不足错误:

Error: cannot allocate vector of size 9.0 Gb

结果矩阵的大小为 C1344,3 = 403,716,544 行和 3 列 - 这是 commn() 函数结果的转置。

我想使用 bigmemory 包创建一个支持 big.matrix 的文件,这样我就可以分配 commn() 函数的结果。我可以创建一个预先分配的大矩阵:

library(bigmemory)
x <- as.character(1:1344)
combos <- 403716544
test <- filebacked.big.matrix(nrow = combos, ncol = 3, 
        init = 0, backingfile = "test.matrix")

但是当我尝试分配值 test <- combn(x, 3) 时我仍然得到同样的结果:Error: cannot allocate vector of size 9.0 Gb

我什至尝试强制 combn(x,3) 的结果但我认为因为 comen() 函数返回错误,所以 big.matrix 函数也不起作用。

test <- as.big.matrix(matrix(combn(x, 3)), backingfile = "abc")
Error: cannot allocate vector of size 9.0 Gb
Error in as.big.matrix(matrix(combn(x, 3)), backingfile = "abc") : 
  error in evaluating the argument 'x' in selecting a method for function 'as.big.matrix'

有没有办法将这两个功能组合在一起以获得我需要的东西?还有其他方法可以实现这一目标吗?谢谢。

最佳答案

这是我用 R 编写的一个函数,它目前在 LSPM 中找到其(未导出的)主目录。包裹。你给它总的项目数n,选择的项目数r,以及你想要的组合的索引i;它返回与组合 i 对应的 1:n 中的值。

".combinadic" <- function(n, r, i) {

  # http://msdn.microsoft.com/en-us/library/aa289166(VS.71).aspx
  # http://en.wikipedia.org/wiki/Combinadic

  if(i < 1 | i > choose(n,r)) stop("'i' must be 0 < i <= n!/(n-r)!")

  largestV <- function(n, r, i) {
    #v <- n-1
    v <- n                                  # Adjusted for one-based indexing
    #while(choose(v,r) > i) v <- v-1
    while(choose(v,r) >= i) v <- v-1        # Adjusted for one-based indexing
    return(v)
  }

  res <- rep(NA,r)
  for(j in 1:r) {
    res[j] <- largestV(n,r,i)
    i <- i-choose(res[j],r)
    n <- res[j]
    r <- r-1
  }
  res <- res + 1
  return(res)
}

它允许您根据词典索引的值生成每个组合:

> .combinadic(1344, 3, 1)
[1] 3 2 1
> .combinadic(1344, 3, 2)
[1] 4 2 1
> .combinadic(1344, 3, 403716544)
[1] 1344 1343 1342

因此您只需循环 1:403716544 并将结果附加到文件中。这可能需要一段时间,但至少是可行的(参见德克的回答)。您可能还需要在多个循环中执行此操作,因为向量 1:403716544 不适合我的机器上的内存。

或者您可以将 R 代码移植到 C/C++ 并在那里进行循环/写入,因为它会快很多

关于r - 使用combn()和bigmemory包生成一个非常大的字符串组合矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4493287/

相关文章:

r - 使用 for 循环进行矩阵计算

r - 使用三点参数时的 list(...) 与 as.list(...)

algorithm - 如何以最佳方式将向量分组到易于描述的组中?

algorithm - 分组组合算法

java - hadoop运行程序出错?

tensorflow - 在大数据上运行 Tensorflow

r - 用 ggplot2 绘制决策边界?

r - 如何使用最新版本的 R RDCOMClient 从 Outlook 发送邮件?

algorithm - 有多少组 4 个数的异或等于 0?

python - 如何将 Pandas 中的一列扩展为多列?