r - 向量中元素的组合
r - combinations from elements in vector
给定向量:
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)
您似乎想要排列,而不是组合。尝试包 combinat
:
中的函数 permn()
# 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
给定向量:
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)
您似乎想要排列,而不是组合。尝试包 combinat
:
permn()
# 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