笛卡尔乘积数据框在R中 [英] Cartesian product data frame in R
问题描述
我有三个或更多的独立变量表示为R向量,如下所示:
I have three or more independent variables represented as R vectors, like so:
A <- c(1,2,3)
B <- factor(c('x','y'))
C <- c(0.1,0.5)
,我想把所有的笛卡尔乘积放在数据框中,如下所示:
and I want to take the Cartesian product of all of them and put the result into a data frame, like this:
A B C
1 x 0.1
1 x 0.5
1 y 0.1
1 y 0.5
2 x 0.1
2 x 0.5
2 y 0.1
2 y 0.5
3 x 0.1
3 x 0.5
3 y 0.1
3 y 0.5
我可以通过手动写入 rep
d <- data.frame(A = rep(A, times=length(B)*length(C)),
B = rep(B, times=length(A), each=length(C)),
C = rep(C, each=length(A)*length(B))
但是,必须有一个更优雅的方式来做,是吗?<$ c $在 itertools
中的c>产品作业的一部分,但我找不到任何方式来吸收迭代器的输出并将其放入数据帧。任何建议?
but there must be a more elegant way to do it, yes? product
in itertools
does part of the job, but I can't find any way to absorb the output of an iterator and put it into a data frame. Any suggestions?
p.s。这个计算的下一步看起来像
p.s. The next step in this calculation looks like
d$D <- f(d$A, d$B, d$C)
所以如果你知道一次同时执行这两个步骤的方法,那也是有帮助的。
so if you know a way to do both steps at once, that would also be helpful.
推荐答案
可以使用 expand.grid(A,B,C)
编辑:使用do.call实现第二部分的替代方法是功能mdply。这里是代码
an alternative to using do.call to achieve the second part, is the function mdply. here is the code
d = expand.grid(x = A, y = B, z = C)
d = mdply(d, f)
使用简单的函数粘贴来说明其用法,你可以尝试
to illustrate its usage using a trivial function 'paste', you can try
d = mdply(d, 'paste', sep = '+');
这篇关于笛卡尔乘积数据框在R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!