4
$\begingroup$

I have six tables of data say

t1 = {{1, 4}, {2, 2}, {3, 3}};
t2 = {{1, 3}, {2, 5}, {3, 5}};
t3 = {{1, 2}, {2, 7}, {3, 4}};
t4 = {{1, 5}, {2, 8}, {3, 9}};
t5 = {{1, 8}, {2, 1}, {3, 8}};
t6 = {{1, 9}, {2, 5}, {3, 3}};

I want to add all data such that first data in the brace remains same but the second data are added up.

For an example:

tsum1 = {{1,31},{2,34},{3,32}};

How can I do it in Mathematica? Thanks in advance.

$\endgroup$
1
  • $\begingroup$ how did you get {{1,31},{2,34},{3,32}}? I get {{1, 31}, {2, 28}, {3, 32}} $\endgroup$
    – Nasser
    Jan 11, 2017 at 4:03

5 Answers 5

5
$\begingroup$

Add the tables and then divide the numbers in the first column by the number of lists you added:

MapAt[#/6 &, t1 + t2 + t3 + t4 + t5 + t6, {{All, 1}}]
(* {{1, 31}, {2, 28}, {3, 32}} *)

#/6 & is a function that returns the argument divided by 6, and this function is applied to the first column.

$\endgroup$
5
$\begingroup$

Basically operationally equivalent to kglr's second option, but sans Transpose:

With[{d = {t1, t2, t3, t4, t5, t6}},
 Thread@{First /@ First@d, Last /@ # & /@ d // Total}
 ]
$\endgroup$
5
$\begingroup$

Some approaches:

  • for this specific example

    {#1/6, #2} & @@@ (t1 + t2 + t3 + t4 + t5 + t6)
    
  • using Sow and Reap:

    ts = {t1, t2, t3, t4, t5, t6}
    Reap[Sow[#2, #1] & @@@ Join @@ (ts), _, {#1, Total@#2} &][[-1]]
    
  • using Association and Merge:

    ds =Rule @@@ # & /@ ts;
    List @@@ Normal[Merge[ds, Total]]
    
$\endgroup$
5
$\begingroup$
t = {t1, t2, t3, t4, t5, t6}
asc = Association /@ (Rule @@@ # &/@ t)

List@@@Normal@Merge[Total][asc]

{{1, 31}, {2, 28}, {3, 32}}

or

Transpose@{t[[1, All, 1]], Total@t[[All, All, 2]]}

{{1, 31}, {2, 28}, {3, 32}}

or

♯0 = {#/6, #2} & @@@ +## & @@ # &;
♯0 @ t

{{1, 31}, {2, 28}, {3, 32}}

$\endgroup$
3
$\begingroup$

May be a little bit hacky, but this seems to work

data = ToExpression["t" <> ToString[#]] & /@ Range[6];
{data[[1, #, 1]], Total[data[[All, #, 2]]]} & /@ Range[3]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ Ah... that can work. $\endgroup$ Jan 11, 2017 at 4:07

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.