How to create a combination with 2 datasets in R

How to create a data set with any possible combination of two data sets?

For example, there would be two datasets with specific columns:

ds1 = letters[1:4] ds2 = letters[5:8] 

There are also meanings associated with each letter if it affects anything (I don't think it should be).

 ds1 = data.frame(a=letters[1:4],b=1:4) ds2 = data.frame(a=letters[5:8],b=5:8) 

In the last dataset, I would like each combination of ds1 and ds2 (e.g. ae, af, ag, etc.)

At first, I thought about using merge , so I tried to do this, but that didn't work. I thought that for the loop would probably be the answer, but I'm not sure how I will start.

Suggestions? Thanks!

+4
source share
2 answers

Perhaps you want expand.grid() ? expand.grid() creates a data frame from all combinations of provided vectors or factors. letters() contains 26 lowercase letters of the alphabet, so we can index the first 4 (A - D) and the next four (E - H) to go to expand.grid()

 > expand.grid(letters[1:4], letters[5:8]) Var1 Var2 1 ae 2 be 3 ce 4 de 5 af 6 bf 7 cf 8 df 9 ag 10 bg 11 cg 12 dg 13 ah 14 bh 15 ch 16 dh 
+8
source

It seems that you want the Cartesian product of ds1 and ds2. To do this, use merge(ds1, ds2, by=NULL) .

+6
source

All Articles