笛卡尔积数据框 [英] Cartesian product data frame
问题描述
我有三个或更多个表示为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
:
I can do this by manually writing out calls to 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))
但是必须有一种更优雅的方法,是吗? itertools
中的c> product 可以完成部分工作,但是我找不到任何方法吸收迭代器的输出并将其放入数据帧。有什么建议吗?
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来实现第二部分的另一种方法是使用plyr包中的mdply函数。这是代码
an alternative to using do.call to achieve the second part, is the function mdply from the package plyr. here is the code
library(plyr)
d = expand.grid(x = A, y = B, z = C)
d = mdply(d, f)
为了说明使用简单函数 paste的用法,您可以尝试
to illustrate its usage using a trivial function 'paste', you can try
d = mdply(d, 'paste', sep = '+');
这篇关于笛卡尔积数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!