Previous Page | Next Page

Finding Shortcuts in Programming

Performing More Than One Action in an IF-THEN Statement

Several changes are needed in the observations for Madrid and Amsterdam. One way to select those observations is to evaluate an IF condition in a series of IF-THEN statements, as follows:

   /* multiple actions based on the same condition */
data updatedattractions;
   set mylib.attractions;
   if City = 'Madrid' then Museums = 3;
   if City = 'Madrid' then Other = 2;
   if City = 'Amsterdam' then TourGuide = 'Vandever';
   if City = 'Amsterdam' then YearsExperience = 4;
run;

To avoid writing the IF condition twice for each city, use a DO group in the THEN clause, for example:

IF condition THEN
DO;
...more SAS statements...
END;

The DO statement causes all statements following it to be treated as a unit until a matching END statement appears. A group of SAS statements that begin with DO and end with END is called a DO group.

The following DATA step replaces the multiple IF-THEN statements with DO groups:

options pagesize=60 linesize=80 pageno=1 nodate;
   /* a more efficient method */
data updatedattractions2;
   set mylib.attractions;
   if City = 'Madrid' then
      do;
         Museums = 3;
         Other = 2;
      end;
   else if City = 'Amsterdam' then
      do;
         TourGuide = 'Vandever';
         YearsExperience = 4;
      end;
run;

proc print data=updatedattractions2;
   title 'Data Set MYLIB.UPDATEDATTRACTIONS';
run;

Using DO Groups to Produce a Data Set

                       Data Set MYLIB.UPDATEDATTRACTIONS                       1

                                                       Tour           Years
  Obs    City         Museums    Galleries    Other    Guide       Experience

   1     Rome            4           3          .      D'Amico          2    
   2     Paris           5           .          1      Lucas            5    
   3     London          3           2          .      Wilson           3    
   4     New York        5           1          2      Lucas            5    
   5     Madrid          3           .          2      Torres           4    
   6     Amsterdam       3           3          .      Vandever         4    

Using DO groups makes the program faster to write and easier to read. It also makes the program more efficient for SAS in two ways:

  1. The IF condition is evaluated fewer times. (Although there are more statements in this DATA step than in the preceding one, the DO and END statements require very few computer resources.)

  2. The conditions City = 'Madrid' and City = 'Amsterdam' are mutually exclusive, as condensing the multiple IF-THEN statements into two statements reveals. You can make the second IF-THEN statement part of an ELSE statement; therefore, the second IF condition is not evaluated when the first IF condition is true.

Previous Page | Next Page | Top of Page