r - r - 向量中元素的组合
问题描述
给定向量:
a <- c(1,2,3)
我正在尝试计算包含 a 中元素组合的所有向量,即:
list(
a[c(1,2,3)],
a[c(1,3,2)],
a[c(2,1,3)],
a[c(2,3,1)],
a[c(3,1,2)],
a[c(3,2,1)])
这可以通过以下方式重现:
df <- expand.grid(rep(list(a), length(a)))
nunique <- apply(df, 1, function(x) length(unique(x)))
df <- df[nunique == ncol(df), ]
as.list(as.data.frame(t(df)))
我尝试使用 the 来执行此操作,expand.grid
但是此函数提供了可以重复元素的排列,这会导致数据集超大并从下面给出错误。
我已经看到了与此类似的问题,但未能找到不会产生错误的快速解决方案:
Error: cannot allocate vector of size 37.3 Gb
该错误可以重现为:
a <- c(1,2,3,4,5,6,7,8,9,10)
解决方案
您似乎想要排列,而不是组合。尝试permn()
包中的功能combinat
:
# Your first example:
combinat::permn(c(1, 2, 3))
#> [[1]]
#> [1] 1 2 3
#>
#> [[2]]
#> [1] 1 3 2
#>
#> [[3]]
#> [1] 3 1 2
#>
#> [[4]]
#> [1] 3 2 1
#>
#> [[5]]
#> [1] 2 3 1
#>
#> [[6]]
#> [1] 2 1 3
# Your second example
res <- combinat::permn(c(1,2,3,4,5,6,7,8,9,10))
不过,这确实需要一段时间。当然,对象本身会很大:
system.time(res <- combinat::permn(c(1,2,3,4,5,6,7,8,9,10)))
#> user system elapsed
#> 14.661 0.448 15.346
pryr::object_size(res)
#> 639 MB
推荐阅读
- java - 循环在java中为mongodb覆盖update(“$ max”)的值
- r - 如何为双变量数据(例如,绘图)生成 3D 联合概率分布?
- jenkins - Jenkins Pipeline阶段跳过基于管道中定义的groovy变量
- wordpress - 一个轻量级的 Wordpress 需要一分钟才能加载
- php - 数据库在 PHP Codeigniter 中返回一个空的 Array()
- c# - 无法在 MVC 5 中检查授权和使用会话超时
- javascript - 尝试使用 Function 对象使用尾递归
- javascript - 有没有办法使用 Three.js 将 3D 模型导出为 PNG 图像
- shell - 有没有一种方法可以让我在另一台服务器上使用 shell 脚本访问、使用和操作来自一台服务器的文件>
- firebase - 如何优化每次应用启动时的 Firestore 读取