Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cartesian product with dplyr R

I'm trying to find the dplyr function for cartesian product. I've two simple data.frame with no common variable:

x <- data.frame(x=c("a","b","c")) y <- data.frame(y=c(1,2,3)) 

I would like to reproduce the result of

merge(x,y)    x y 1 a 1 2 b 1 3 c 1 4 a 2 5 b 2 6 c 2 7 a 3 8 b 3 9 c 3 

I've already looked for this (for example here or here) without finding anything useful.

Thank you very much

like image 577
Luca Monno Avatar asked Apr 05 '17 10:04

Luca Monno


1 Answers

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 
like image 117
Gregor Sturm Avatar answered Oct 11 '22 13:10

Gregor Sturm