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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…