Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a very large data set (around 3000) that looks like:

{{1749.08, 580.}, {1749.17, 626.}, {1749.25, 700.}, {1749.33, 
  557.}, {1749.42, 850.}, {1749.5, 835.}, {1749.58, 948.}, {1749.67, 
  663.}....

The first number is the year plus the month/12. So I want to iterate over all the list adding the second part for each year

So example using data above:

For year 1749: 580+626+700+557+850+835+948+663

I know I have to use a for loop but I can't figure out the syntax. Can anyone lend a helping hand?

share|improve this question

marked as duplicate by Mr.Wizard Mar 12 at 0:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
This question seems to be a duplicate, with the exception of the need to Round (or Floor) the first column data. I have marked it as such. If anyone disagrees please comment and/or vote to reopen. –  Mr.Wizard Mar 12 at 0:59
    
Closely related: (4332) –  Mr.Wizard Mar 12 at 1:01

2 Answers 2

up vote 0 down vote accepted

One way is to gather the years by using Floor and then adding up the values for each year.

data = {{1749.08, 580.}, {1749.17, 626.}, {1749.25, 
    700.}, {1749.33, 557.}, {1749.42, 850.}, {1749.5, 835.}, {1749.58,
     948.}, {1749.67, 663.}, {1750.00, 653.}};
Total[Part[#, All, 2]] & /@ GatherBy[data, Floor[First[#]] &]
(* {5759., 653.} *)
share|improve this answer
    
This works great, but I'm a little confused as to why for this output it has the 653? –  user1985351 Mar 12 at 0:53
    
@user1985351 I added a fake value for the year 1750 as last element in data. So what you see is the sum of all entries for the year 1749 and the sum for all entries of the year 1750. –  halirutan Mar 12 at 0:55
    
Oh I see that now. Thank you for your help! –  user1985351 Mar 12 at 0:58
data = {{1749.08, 580.}, {1749.17, 626.}, {1749.25, 700.}, {1749.33, 
   557.}, {1749.42, 850.}, {1749.5, 835.}, {1749.58, 948.}, {1749.67, 
   663.}, {1751.66, 10}, {1751.77, 20}}

Total /@ GatherBy[data, IntegerPart[#[[1]]] &][[All, All, 2]]

(* {5759.,30} *)

Note the data might be a bit ambiguous: if the month is 12, the year gets bumped to the next. Is that really what you want?

share|improve this answer

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