10
$\begingroup$

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?

$\endgroup$

4 Answers 4

13
$\begingroup$

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]]
$\endgroup$
2
  • $\begingroup$ I thank you very much, exactly what I needed!!!! $\endgroup$
    – Jacccy
    Nov 11, 2016 at 12:00
  • $\begingroup$ @Jacccy there are many ways to do things in Mma. Have fun playing. I find it the best way to learn. :) $\endgroup$
    – ubpdqn
    Nov 11, 2016 at 12:02
12
$\begingroup$

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}}}

$\endgroup$
10
$\begingroup$

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}}}

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

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.