# Join lists by observing x-value

Hi everybody I have as a small test with two datasets (normally I have 100 datasets with 4100 brackets):

Dataset1={{20,1},{30, 1.3}, {40, 0.4}, {50, 0.9}}
Dataset2={{30, 1.2}, {40, 1}, {50, 0.4}, {80, 1},{90,1}}


I want to combine both lists by joining the y-values to the correspondiong x value

ResultData={{20,{1}},{30, {1.3,1.2}}, {40,{ 0.4,1}}, {50, {0.9,0.4},{80, {1}},{90,{1}}}


Has somebody an idea?

A couple of ways:

ds = Dataset1~Join~Dataset2
List @@@ Normal[GroupBy[ds, First -> Last]]
Last@Reap[Sow[#2, #1] & @@@ ds, _, List]


All yield:

{{20, {1}}, {30, {1.3, 1.2}}, {40, {0.4, 1}}, {50, {0.9,
0.4}}, {80, {1}}, {90, {1}}}


or

d1 = Rule @@@ Dataset1
d2 = Rule @@@ Dataset2
List @@@ Normal[Merge[{d1, d2}, Join]]

• I thank you very much, exactly what I needed!!!! – Jacccy Nov 11 '16 at 12:00
• @Jacccy there are many ways to do things in Mma. Have fun playing. I find it the best way to learn. :) – ubpdqn Nov 11 '16 at 12:02

One way is to use GatherBy and then coerce the resulting list into the form you require:

d1 = {{20, 1}, {30, 1.3}, {40, 0.4}, {50, 0.9}};
d2 = {{30, 1.2}, {40, 1}, {50, 0.4}, {80, 1}, {90, 1}};

{#[[1, 1]], #[[All, 2]]} & /@ GatherBy[Join[d1, d2], First]


{{20, {1}}, {30, {1.3, 1.2}}, {40, {0.4, 1}}, {50, {0.9, 0.4}}, {80, {1}}, {90, {1}}}

A different way:

d = GatherBy[Dataset1~Join~Dataset2, First]
{Max[#1], #2} & @@@ Transpose /@ d


{{20, {1}}, {30, {1.3, 1.2}}, {40, {0.4, 1}}, {50, {0.9, 0.4}}, {80, {1}}, {90, {1}}}

• esp useful if one has older versions +1 :) – ubpdqn Nov 11 '16 at 12:03
• @ubpdqn I'm a simple man, I think the old ways ;) – corey979 Nov 11 '16 at 12:13

Rule based option:

Join[Dataset1, Dataset2] //. {
{a___, {x_, {y__}}, b___, {x_, y2_}, c___} :> {a, {x, {y, y2}}, b, c},
{a___, {x_, y1_}, b___, {x_, y2_}, c___} :> {a, {x, {y1, y2}}, b, c}
}


To understand how it works it's easier to read the second rule first. If there can't be more than two elements with the same x value then the second rule is enough.