Calculate intermediate sum and total sum using accumulate and reduce functions. You can find the examples in r documentation.
accumulate(x,function) #return intermediate results. use the intermediate sum at each step to find the left amount.
reduce(x,function) #return final result only.