cartesian product with dplyr R
Use crossing from the tidyr
package:
x <- data.frame(x=c("a","b","c"))
y <- data.frame(y=c(1,2,3))
crossing(x, y)
Result:
x y
1 a 1
2 a 2
3 a 3
4 b 1
5 b 2
6 b 3
7 c 1
8 c 2
9 c 3
Apologies to all: the below example does not appear to work with data.frames or data.tables.
When x and y are database tbl
s (tbl_dbi
/ tbl_sql
) you can now also do:
full_join(x, y, by = character())
Added to dplyr at the end of 2017, and also gets translated to a CROSS JOIN
in the DB world. Saves the nastiness of having to introduce the fake variables.