SAS (Base SAS)+
data scores;
input id score;
datalines;
1 10
2 15
3 20
4 25
5 30
;
run;
data cumulative;
set scores;
retain cum_sum cum_prod cum_avg count;
if _n_ = 1 then do;
cum_sum = score;
cum_prod = score;
count = 1;
cum_avg = score;
end;
else do;
cum_sum + score;
cum_prod = cum_prod * score;
count + 1;
cum_avg = cum_sum / count;
end;
run;- In SAS, cumulative operations live inside a DATA step with a
RETAINstatement holding the running totals. - We initialise all accumulators on the first row:
if _n_ = 1 then do; cum_sum = score; cum_prod = score; count = 1; cum_avg = score; end;. - On every subsequent row we update each accumulator:
cum_sum + score;adds to the running sum using the sum-statement shortcut. cum_prod = cum_prod * score;multiplies the running product by the new value — no shortcut operator exists for multiplication.count + 1;counts how many rows have been processed;cum_avg = cum_sum / count;derives the running average.- The sum-statement form (
var + expr;) retains the variable and treats missing values as zero — a quiet convenience built into the SAS language. - We run and verify the CUMULATIVE dataset:
cum_sumgrows monotonically,cum_prodmultiplies through, andcum_avgis the running mean.