You can process observations
conditionally by using the subsetting IF or IF-THEN statements, or
the SELECT statement, with the temporary variables FIRST.
variable and
LAST.
variable (set up during
BY-group processing). For example, you can use them to perform calculations
for each BY group and to write an observation when the first or the
last observation of a BY group has been read into the program data
vector.
The following example
computes annual payroll by department. It uses IF-THEN statements
and the values of FIRST.
variable and
LAST.
variable automatic variables
to reset the value of PAYROLL to 0 at the beginning of each BY group
and to write an observation after the last observation in a BY group
is processed.
options pageno=1 nodate linesize=80 pagesize=60;
data salaries;
input Department $ Name $ WageCategory $ WageRate;
datalines;
BAD Carol Salaried 20000
BAD Elizabeth Salaried 5000
BAD Linda Salaried 7000
BAD Thomas Salaried 9000
BAD Lynne Hourly 230
DDG Jason Hourly 200
DDG Paul Salaried 4000
PPD Kevin Salaried 5500
PPD Amber Hourly 150
PPD Tina Salaried 13000
STD Helen Hourly 200
STD Jim Salaried 8000
;
proc print data=salaries;
run;
proc sort data=salaries out=temp;
by Department;
run;
data budget (keep=Department Payroll);
set temp;
by Department;
if WageCategory='Salaried' then YearlyWage=WageRate*12;
else if WageCategory='Hourly' then YearlyWage=WageRate*2000;
/* SAS sets FIRST.variable to 1 if this is a new */
/* department in the BY group. */
if first.Department then Payroll=0;
Payroll+YearlyWage;
/* SAS sets LAST.variable to 1 if this is the last */
/* department in the current BY group. */
if last.Department;
run;
proc print data=budget;
format Payroll dollar10.;
title 'Annual Payroll by Department';
run;
Output from Conditional BY-Group Processing
Annual Payroll by Department 1
Obs Department Payroll
1 BAD $952,000
2 DDG $448,000
3 PPD $522,000
4 STD $496,000