5
$\begingroup$

I have three tables of data say

t1 = {{1, 2}, {2, 3}, {3, 4}};
t2 = {{1, 3}, {2, 3}, {3, 5}};
t3 = {{1, 3}, {2, 3}};

First I want to add t1 and t2 such that first data in the brace remains same but the second data of the two tables are added up.

For an example:

tsum1 = {{1,5},{2,6},{3,9}};

How can I do it in Mathematica?

If I want to add t1, t2 and t3 (t3 has less number of data set than t1 and t2) such that first data points remain same but the second ones are added up.

For an example

tsum2 = {{1,8},{2,9},{3,9}};

How can I do it with Mathematica?

$\endgroup$

3 Answers 3

6
$\begingroup$
t1 = {{1, 2}, {2, 3}, {3, 4}};
t2 = {{1, 3}, {2, 3}, {3, 5}};
t3 = {{1, 3}, {2, 3}};

sum[x : (_?ArrayQ ..)] := Module[
  {maxLen, xp, yp},
  maxLen = Max[Length /@ {x}];
  xp = Select[{x}, Length[#] == maxLen &][[1, All, 1]];
  yp = Plus @@ (PadRight[#[[All, 2]], maxLen, 0] & /@ {x});
  Transpose[{xp, yp}]]

tsum1 = sum[t1, t2]

(*  {{1, 5}, {2, 6}, {3, 9}}  *)

tsum2 = sum[t1, t2, t3]

(*  {{1, 8}, {2, 9}, {3, 9}}  *)

EDIT: A more robust approach using ReplaceRepeated

sum2[x : (_?ArrayQ ..)] := (Join @@ {x}) //.
  {s___, {a_, b_}, m___, {a_, c_}, e___} :>
   {s, {a, b + c}, m, e}

tsum1 = sum2[t1, t2]

(*  {{1, 5}, {2, 6}, {3, 9}}  *)

tsum2 = sum2[t1, t2, t3]

(*  {{1, 8}, {2, 9}, {3, 9}}  *)

t4 = {{3, 5}, {1, 3}};

tsum3 = sum2[t1, t2, t4]

(*  {{1, 8}, {2, 6}, {3, 14}}  *)
$\endgroup$
1
  • $\begingroup$ Thanks for the solution $\endgroup$ Nov 8, 2016 at 7:07
2
$\begingroup$

A short one-liner, taking advantage of the second argument of Flatten to perform a ragged transpose:

{First@#1, Tr@#2} & @@@ Flatten[{t1, t2, t3}, {{2}, {3}}]

(Thank to Simon Woods for changing

Thread /@ Flatten[{t1, t2, t3}, {{2}}]

to

Flatten[{t1, t2, t3}, {{2}, {3}}] )
$\endgroup$
2
  • $\begingroup$ Equivalently {First@#1, Tr@#2} & @@@ Flatten[{t1, t2, t3}, {{2}, {3}}] $\endgroup$ Nov 8, 2016 at 17:30
  • $\begingroup$ @SimonWoods. Thank you! I was looking for that, but I still haven't sat down and really figured out that second argument to Flatten (despite the nice answers here), and so I couldn't figure it out. $\endgroup$
    – march
    Nov 8, 2016 at 17:47
1
$\begingroup$

You may use GatherBy and Total. Or GroupBy and KeyValueMap with Total.

{#[[1, 1]], Total@#[[All, 2]]} & /@ GatherBy[Join @@ {t1, t2, t3}, First]

or

KeyValueMap[{#1, Total@#2[[All, 2]]} &]@GroupBy[Join @@ {t1, t2, t3}, First]

both give

{{1, 8}, {2, 9}, {3, 9}}

Hope this helps.

$\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.