r - 如何计算 R 中列表的笛卡尔幂

标签 r algorithm set cartesian-product

我想生成笛卡尔电源 R 中的任意集合。
例如在 Python 中,我会通过以下方式进行:

from itertools import product
c = [1, 2, 3]
n = 2
l = list(product(c, repeat=n))

这导致以下输出。
[(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)]

我对 R 很陌生,所以我想知道是否有一个内置函数可以用来实现这一点。请注意,我对增加功率特别感兴趣(Python 中的重复参数)。

最佳答案

建议的解决方案忽略顺序。您会注意到 expand.grid迭代 每次迭代最左边的元素 ,它产生的顺序与 python 的 itertools.product 不同发电机。观察:

s <- c(1, 2, 3)
n <- 2
do.call("expand.grid", rep(list(s), n))
  Var1 Var2
1    1    1
2    2    1
3    3    1
4    1    2    <-- This is the second result using python's product
5    2    2
6    3    2
7    1    3    <-- This is the third result using python's product
8    2    3
9    3    3

与python解决方案的输出相比:
from itertools import product
c = [1, 2, 3]
n = 2

list(product(c, repeat=n))
[(1, 1),
(1, 2),
(1, 3),
(2, 1),
(2, 2),
(2, 3),
(3, 1),
(3, 2),
(3, 3)]

来自 itertools.product()文档(重点是我的):

The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.



将此与此答案顶部(即最左侧)所述的内容进行比较。

幸运的是,在 R 中生成了完全相同的输出(或任何与此相关的语言)相对容易,因为这些只是重复排列。如果您想构建自己的生成器,例如 python ,该算法根据文档的建议相对简单(即“大致相当于生成器表达式中的嵌套 for 循环”)。

有一些包能够以所需的顺序相当有效地生成这些。他们是 gtools , arrangements , 和 RcppAlgos *.

这是所有三个的代码:
gtools::permutations(3, 2, repeats.allowed = T)

arrangements::permutations(3, 2, replace = T)

RcppAlgos::permuteGeneral(3, 2, T)

作为一个好处,这些解决方案比使用 expand.grid 更有效。 :
system.time(do.call("expand.grid", rep(list(1:7), 8)))
 user  system elapsed 
0.375   0.007   0.382

system.time(RcppAlgos::permuteGeneral(7, 8, T))
 user  system elapsed 
0.057   0.032   0.088

RcppAlgos::permuteCount(7, 8, T)
[1] 5764801

事实上,它们甚至比 python 还要快。解决方案:
import time

def getTime():
     start = time.time()
     list(product([1, 2, 3, 4, 5, 6, 7], repeat = 8))
     end = time.time()
     print(end - start)

getTime()
0.9604620933532715

公平地说,itertools旨在迭代从而提高内存效率,而不是真正意味着一次生成所有结果。

* 我是 RcppAlgos 的作者

关于r - 如何计算 R 中列表的笛卡尔幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59469876/

相关文章:

c - 冒泡排序,使所有以数字 5 结尾的数字按升序排列

flutter - 如何在Dart/Flutter中按字母顺序对Set <String>进行排序?

r - 使用 data.table 按变量分组查找均值差

r - 在 R 中,如何轻松返回类别组合之间的共同唯一元素的比例?

Rf_error 和 Rf_warning 定义

r-如何在highcharter图中设置xlim和ylim范围?

c# - 线段的多边形

树分解算法

Scala:集合中的连续ID

set - 为什么我的集合 A 和集合 B 的 Union 过程返回集合 A 而没有别的?