Compute intermediate totals using Select and Plus in a list

I have to total per year of weekly results of a function which are in a table with 3 rows: one with the result of the function, one with the week number and one with the year number. I am almost sure that combining Select and Total should do it. I didn't find any example (maybe i didn't look well enough) in StackExchange... Edit: Here is a minimal example of the data:

(-429446.   15. 1984.
337.724 16. 1984.
155953. 17. 1984.
221679. 18. 1984.
81618.2 19. 1984.
-420619.    20. 1984.
-870370.    21. 1984.
-902968.    22. 1984.
-873332.    23. 1984.
-602452.    24. 1984.)
• Could you please provide some additional information to your original post? Like - what is the data? What is the desired output format? Have you tried anything so far? – e.doroskevic Feb 9 '16 at 10:27
• Yes, the data is in the form:{{-429134,15,1984},{-112345,16,1984},...{213420,35,2015}} And I tried Table[Select[Total[sTT[[#, 1]]], sTT[[#,3]] == i &], {i, 1984, 2013}] – Xavier_B Feb 9 '16 at 10:33
• Please edit your question to include the input and the desired output. Any code you have writen would also be very much appreciated. – e.doroskevic Feb 9 '16 at 10:35
• I need to sum all data of the same year which are in the first column of the matrix which is 735 rows and 3 columns – Xavier_B Feb 9 '16 at 10:37
• How about: 26574 and linked topics. – Kuba Feb 9 '16 at 10:59

If your data is called L, this should work:

Transpose[{#[[All, 1, 2]], Total[#[[All, All, 1]], {2}]}] &[GatherBy[L[[All, {1, 3}]], Last]]

More neat though:

Map[Total[L[[#, 1]]] &, PositionIndex[L[[All, 3]]]]

(*To convert to list*)
List @@@ Normal[%]
• I get a Lists of unequal length in Internal`PartitionRagged as output. – Xavier_B Feb 9 '16 at 10:41
• @Xavier_B I edited, does the new thing work? – Coolwater Feb 9 '16 at 10:42
• Yes, it does! Fantastic! I wish I kew Mathematica as you do! – Xavier_B Feb 9 '16 at 10:51
• This is great, a slightly shorter version would be: {#[[1, 3]], First@Total@#} & /@ GatherBy[L, Last] – Jason B. Feb 9 '16 at 10:52

Example:

(*pseudo data*)
data = {{-429134, 15, 1984}, {-112345, 16, 1984}, {213420, 35, 2015}}

(*operation*)
f[year_] := Total @ (First @ # & /@ Select[data, Last[#] == year &])
f[#] & /@ {1984, 2015}

Output:

{-541479, 213420}

Reference:

• Works also, but still needs to tierate on the year from 1984 to 2015 – Xavier_B Feb 9 '16 at 10:54
• @Xavier_B please see edit. – e.doroskevic Feb 9 '16 at 11:04

If you have version 10, you can also use GroupBy:

data={{a, w1, y1}, {b, w2, y1},  {c, w1, y2}, {d, w2, y2}, {e, w3, y2}, {f, w4, y3}};
List@@@Normal@GroupBy[data, Last->First, Total]

{{y1,a+b}, {y2,c+d+e}, {y3,f}}