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
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))
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. 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.
f
is a placeholder for one of several different hairy mathematical calculations, but for purposes of this question, I think the thing you need to know is that they all take N vectors of appropriate type and produce one vector; all inputs must be the same length, and the output is also that length. – Sigmondata.table
, notdata table
. – Incondite