Cartesian product data frame
Solution 1:
You can use expand.grid(A, B, C)
EDIT: an alternative to using do.call
to achieve the second part, is the function mdply
from the package plyr
:
library(plyr)
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 = '+');
Solution 2:
There's a function manipulating dataframe, which is helpful in this case.
It can produce various join(in SQL terminology), while Cartesian product is a special case.
You have to convert the varibles to data frames first, because it take data frame as parameters.
so something like this will do:
A.B=merge(data.frame(A=A), data.frame(B=B),by=NULL);
A.B.C=merge(A.B, data.frame(C=C),by=NULL);
The only thing to care about is that rows are not sorted as you depicted. You may sort them manually as you wish.
merge(x, y, by = intersect(names(x), names(y)),
by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all,
sort = TRUE, suffixes = c(".x",".y"),
incomparables = NULL, ...)
"If by or both by.x and by.y are of length 0 (a length zero vector or NULL), the result, r, is the Cartesian product of x and y"
see this url for detail: http://stat.ethz.ch/R-manual/R-patched/library/base/html/merge.html