2

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.)
Xavier_B
  • 193
  • 6
  • 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 09 '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 09 '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 09 '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 09 '16 at 10:37
  • How about: 26574 and linked topics. – Kuba Feb 09 '16 at 10:59

3 Answers3

3

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[%]
Coolwater
  • 20,257
  • 3
  • 35
  • 64
2

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:

@ /@ # etc.
First
Last
Select

e.doroskevic
  • 5,959
  • 1
  • 13
  • 32
2

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

kglr
  • 394,356
  • 18
  • 477
  • 896