给出向量:
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)))
我尝试使用expand.grid
进行此操作,但是此函数提供了可以重复元素的排列,这会导致特大数据集并从下面给出错误。
我看到了与此类似的问题,但是没有找到一种不会产生错误的快速解决方案:
Error: cannot allocate vector of size 37.3 Gb
该错误可被复制为:
a <- c(1,2,3,4,5,6,7,8,9,10)
答案 0 :(得分:2)
您似乎想要排列,而不是组合。尝试使用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