首页 > 解决方案 > 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)

标签: rcombinationspermutationlarge-data

解决方案


您似乎想要排列,而不是组合。尝试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

推荐阅读