Search code examples
loopsmathsassas-macroaccumulate

Accumulated Balance in SAS


I have this dataset in SAS:

id column_a column_b
1 10 8
1 7 1
1 0 10
2 8 8
2 10 1
2 10 0

I need to calculate an accumulated balance per id, column_a (-) column_b. Output wanted:

id column_a column_b balance
1 10 8 2
1 7 1 8
1 0 10 -2
2 8 8 0
2 10 1 9
2 10 0 19

Solution

  • First let's convert your listing into an actual dataset so we have something to work with. Let's use a little more descriptive variable names.

    data have;
      input id deposit withdrawal ;
    cards;
    1 10 8
    1 7 1
    1 0 10
    2 8 8
    2 10 1
    2 10 0
    ;
    

    Now just retain a variable so its value does not get set to missing at the start of each iteration of the data step.

    Let's add another variable so it is clearer where the running total came from. Again let's use some variable names that are a little bit descriptive. Perhaps OPEN for the value before the deposit and withdrawal are accounted for and CLOSE for afterwards. Retain the CLOSE value so it is available to become the OPEN value for the next observation.

    data want;
      set have;
      by id;
      if first.id then open=0;
      else open=close;
      close = sum(open,deposit,-withdrawal);
      retain close;
    run;
    

    Result

    OBS    id    deposit    withdrawal    open    close
    
     1      1       10           8          0        2
     2      1        7           1          2        8
     3      1        0          10          8       -2
     4      2        8           8          0        0
     5      2       10           1          0        9
     6      2       10           0          9       19
    

    Once you see how it works you can simplify by using a SUM statement (which implies that its target variable is retained).

    data want;
      set have;
      by id;
      if first.id then balance=0;
      balance + (deposit-withdrawal);
    run;