在R中有没有类似于expand.grid()函数的Python函数?提前谢谢。
(编辑)下面是此R函数的说明和一个示例。
Create a Data Frame from All Combinations of Factors
Description:
Create a data frame from all combinations of the supplied vectors
or factors.
> x <- 1:3
> y <- 1:3
> expand.grid(x,y)
Var1 Var2
1 1 1
2 2 1
3 3 1
4 1 2
5 2 2
6 3 2
7 1 3
8 2 3
9 3 3
(EDIT2)下面是rpy包的一个示例。我希望获得相同的输出对象,但不使用R:
>>> from rpy import *
>>> a = [1,2,3]
>>> b = [5,7,9]
>>> r.assign("a",a)
[1, 2, 3]
>>> r.assign("b",b)
[5, 7, 9]
>>> r("expand.grid(a,b)")
{'Var1': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'Var2': [5, 5, 5, 7, 7, 7, 9, 9, 9]}
Python 2012年2月9日:我真的被迷住了。Lev Levitsky在他的回答中给出的代码对我不起作用:
>>> a = [1,2,3]
>>> b = [5,7,9]
>>> expandgrid(a, b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in expandgrid
NameError: global name 'itertools' is not defined
但是似乎已经安装了itertools模块(输入from itertools import *
不会返回任何错误消息)
https://stackoverflow.com/questions/12130883
复制相似问题