How would I create a dataset with every possible combination from two datasets?
For example, there would be 2 datasets with specific columns in mind:
ds1 = letters[1:4]
ds2 = letters[5:8]
There are also values associated with each letter if that would affect anything (I don't think it should, though)
ds1 = data.frame(a=letters[1:4],b=1:4)
ds2 = data.frame(a=letters[5:8],b=5:8)
In the final dataset, I'd like for there to be every combination of ds1
and ds2
(eg. ae, af, ag, etc.)
At first I thought of using merge
, so I tried doing so, but it didn't work. I was thinking that a for-loop would probably be the answer, but I'm not sure as to how I would start.
Suggestions? Thanks!
Perhaps you want expand.grid()
? expand.grid()
creates a data frame from all combinations of the supplied vectors or factors. letters()
contains the 26 lower case letters of the alphabet so we can index the first 4 (A - D) and next four (E - H) to pass into expand.grid()
> expand.grid(letters[1:4], letters[5:8])
Var1 Var2
1 a e
2 b e
3 c e
4 d e
5 a f
6 b f
7 c f
8 d f
9 a g
10 b g
11 c g
12 d g
13 a h
14 b h
15 c h
16 d h
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With