views:

430

answers:

2

Hello programming guru's

I am looking for an way to create a summary variable in SAS that will automatically add each row observation until a condition is met. I would need to be able to start and stop and reset this variable if necessary.

Thanks a lot

-sasnewbie

+3  A: 

Use Retain!

data test;
set test;
retain VarSummary;
VarSummary+YourVar;
if condition then VarSummary=SummatElse;
run;

Hope this makes sense!

Bazil
A: 

If you are going to use a statement like

VarSummary + 1  ;

OR

VarSummary + <expression> ;

then you don't actually need a RETAIN statement.

Also, if you use the BY statement in your DATA STEP, you have access to variables FIRST and LAST (The data must be sorted by the BY variable). FIRST and LAST either have a value of 1 or 0. When the BY variable is on the first value FIRST. = 1 and when it is on the last value LAST. = 1. They can both be equal to 1 when there is only 1 byVariable record and they can both be equal to 0 when there is more than 2 byVariable records (when on the middle records).

FIRST and LAST can help determine when to reset your RETAINed variables. (FIRST and LAST will be in the PDV, but will not be written to the output data set, so there is no need to DROP them).

Example

(The result of this example would probably be done with a PROC, but I hope this demonstrates how FIRST and LAST can be used)

proc sort data=sasuser.laguardia out=work.dest;
 by dest ;
run ;

data work.destination_summary (keep=dest dest_count total_count) ;
 set work.dest ;
 by dest ;

 total_count + 1 ;

 if first.dest then dest_count = 1 ;
 if not first.dest and not last.dest then dest_count + 1 ;
 if last.dest then do ;
  dest_count + 1 ;
  output ;
 end ;
run ;

proc print data=work.destination_summary label noobs ;
 var dest dest_count total_count;
 label Dest="Destination"
   dest_count="Count" 
   total_count= "Total Count";
run ;
CarolinaJay65