Discussion:
Cumulative Sum
(too old to reply)
Mindy
2006-04-21 02:23:52 UTC
Permalink
Hi, all,

I want to calculate the cumulative sum of number by group&var.
group var number Result: csum
1 x 1 1
1 x 2 3
1 x 3 6
1 y 1 1
1 y 2 3
1 y 3 6
1 z 1 1
1 z 2 3
2 x 1 1
2 x 2 3
2 x 3 6
2 y 1 1
2 y 2 3
How can I do this in SAS? Thank you very much.

Mindy
n***@gmail.com
2006-04-21 03:24:33 UTC
Permalink
hi mindy,

give this a try

data test;
input group var $ number result;
cards;
1 x 1 1
1 x 2 3
1 x 3 6
1 y 1 1
1 y 2 3
1 y 3 6
1 z 1 1
1 z 2 3
2 x 1 1
2 x 2 3
2 x 3 6
2 y 1 1
2 y 2 3
;
proc sort data=test;
by group var;
run;
data new;
set test;
by group var;
retain cusum 0;
if first.var then do;
cusum=0;
end;
cusum+number;
if last.var;
run;
proc print data=new;
run;


--nevin
LWn
2006-04-21 06:15:50 UTC
Permalink
Post by n***@gmail.com
hi mindy,
data new;
set test;
by group var;
retain cusum 0;
if first.var then do;
cusum=0;
end;
cusum+number;
if last.var;
run;
proc print data=new;
run;
You actually don't even need the retain statement.
Test this:

data new;
set test;
by group var;
if first.var then cusum=0;
cusum+number;
* if last.var;
run;

/ LWn
Rahul
2006-04-21 12:32:25 UTC
Permalink
Hi Mindy,

You can use below code to do this:

data test;
input grp var $1. num;
cards;
1 x 1
1 x 2
1 x 3
1 y 1
1 y 2
1 y 3
1 z 1
1 z 2
2 x 1
2 x 2
2 x 3
2 y 1
2 y 2
3 y 1
3 y 3
;
run;

proc sort data=test out=test2;by grp var;run;

data test5;
set test2;
retain cnum 0;
by grp var;
cnum = cnum + num;
if first.var then cnum=num;
run;

proc print data=test5;run;
toby dunn
2006-04-21 13:34:36 UTC
Permalink
Mindy ,

Like many things in SAS there are a number of ways to do this. But lets
stick to the basic data step.

Assuming you want the entire data set in tack and want to add a cumulative
sum variable:

Data Need ;
set Have ;
by Group Var ;
CumSum + Number ;
run ;


Now if you wanted the last observation with the cumulative sum var :


Data Need ;
set Have ;
by Group Var ;

CumSum + Number ;

if last.Var then do ;
output ;
CumSum = 0 ;
end ;

run ;


Toby Dunn





From: Mindy <***@GMAIL.COM>
Reply-To: Mindy <***@GMAIL.COM>
To: SAS-***@LISTSERV.UGA.EDU
Subject: Cumulative Sum
Date: Thu, 20 Apr 2006 19:23:52 -0700

Hi, all,

I want to calculate the cumulative sum of number by group&var.
group var number Result: csum
1 x 1 1
1 x 2 3
1 x 3 6
1 y 1 1
1 y 2 3
1 y 3 6
1 z 1 1
1 z 2 3
2 x 1 1
2 x 2 3
2 x 3 6
2 y 1 1
2 y 2 3
How can I do this in SAS? Thank you very much.

Mindy

Loading...