SAS (Base SAS)+
data CLASS;
infile datalines dlm='|' dsd missover;
input Name : $8. Sex : $1. Age : best32. Height : best32. Weight : best32.;
label ;
format ;
datalines4;
Alfred|M|14|69|112.5
Alice|F|13|56.5|84
Barbara|F|13|65.3|98
Carol|F|14|62.8|102.5
Henry|M|14|63.5|102.5
James|M|12|57.3|83
Jane|F|12|59.8|84.5
Janet|F|15|62.5|112.5
Jeffrey|M|13|62.5|84
John|M|12|59|99.5
Joyce|F|11|51.3|50.5
Judy|F|14|64.3|90
Louise|F|12|56.3|77
Mary|F|15|66.5|112
Philip|M|16|72|150
Robert|M|12|64.8|128
Ronald|M|15|67|133
Thomas|M|11|57.5|85
William|M|15|66.5|112
;;;;
run;
*------------------------------------------------------------------------------;
*counter;
*------------------------------------------------------------------------------;
proc sort data=class;
by sex height weight name;
run;
data counter;
set class;
by sex height weight name;
if first.sex then counter=1;
else counter+1;
run;
*------------------------------------------------------------------------------;
*subset of lowest height;
*------------------------------------------------------------------------------;
proc sort data=class;
by sex height;
run;
data lowestheight;
set class;
by sex height;
if first.sex;
keep sex height name;
run;- In SAS, once a dataset is sorted by a variable, the DATA step exposes automatic flags called
first.varandlast.varwhen that variable is named in abystatement. first.sexis TRUE on the first record of each Sex group and FALSE otherwise — exactly the signal we want for a within-group counter.- For the counter example,
proc sort data=class; by sex height weight name;sets a stable order, then the DATA step reads CLASS with that samebylist. if first.sex then counter=1; else counter+1;uses the sum statement form —counter+1automatically retains the counter across rows, so we never have to write an explicitretain.- For the lowest-Height example, sorting by
sex heightand writingif first.sex;on its own line keeps only the first row of each Sex — the one with the smallest Height. - After running, COUNTER has an incrementing counter within each Sex; LOWESTHEIGHT has one row per Sex with the smallest Height.