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

问题描述 投票:0回答:1

我想生成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中的repeat参数)特别感兴趣。

r algorithm set cartesian-product
1个回答
0
投票

感谢@ G.Grothendieck解决了这个问题!

s <- c(1, 2, 3)
n <- 2
do.call("expand.grid", rep(list(s), n))

这是给出正确结果的R代码。

© www.soinside.com 2019 - 2024. All rights reserved.