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 list which has a date and a amount, I need to create a list that has the cummulative total with the date.

I have the following result:

{{{2009, 8, 3}, 1829.}, {{2009, 8, 4}, 1113.}, {{2009, 8, 5}, 730.}, {{2009, 8, 6}, -243.}}

What I need:

 {{{2009, 8, 3}, 1829.}, {{2009, 8, 4}, 2942.}, {{2009, 8, 5}, 3672.}, {{2009, 8, 6}, 3429.}}

I have just spent over an hour trying to figure this out, any help is most appreciated.

share|improve this question

3 Answers 3

up vote 7 down vote accepted
list = {{{2009, 8, 3}, 1829.}, {{2009, 8, 4}, 1113.}, {{2009, 8, 5},730.}, {{2009, 8, 6}, -243.}}

Rest@FoldList[{#2[[1]], (#1 + #2)[[2]]} &, 0, list]

Or

Rest@FoldList[{#2[[1]], Last@Plus@## } &, 0, list]
share|improve this answer
    
Thank you, they both work great. Since I have worked with FoldList before I will go with this one. –  John Jun 8 '12 at 21:54
1  
@John Transpose and Accumulate (both used in b.gatessucks' answer) are very useful functions. If you are not using them yet, you should :) –  belisarius Jun 9 '12 at 3:15

Starting with:

list = {{{2009, 8, 3}, 1829.}, {{2009, 8, 4}, 1113.}, {{2009, 8, 5}, 730.}, {{2009, 8, 6}, -243.}};

I propose:

MapAt[Accumulate, list\[Transpose], 2]\[Transpose]

Which in the Notebook looks like:

Mathematica graphics

Or with in-place modification:

list[[All, 2]] = Accumulate @ list[[All, 2]]; list
share|improve this answer

Something like :

alist = {{{2009, 8, 3}, 1829.}, {{2009, 8, 4}, 1113.}, {{2009, 8, 5},730.}, {{2009, 8, 6}, -243.}};

Transpose[{alist[[All, 1]], Accumulate[alist[[All, 2]]]}]
share|improve this answer
    
@acheong87 Running my code reproduces the requested output; do you get anything different ? –  b.gatessucks Aug 25 '13 at 7:51
    
My mistake; somehow I was getting a list of dates, and a list of cumulative values; my input must have gotten mucked up somewhere. Deleting my comment; already +1'ed. –  Andrew Cheong Aug 26 '13 at 2:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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