SAS Work Shop Statistical Programs   
Handout # 7 College of Agriculture


Topics covered: Retention
Deletion
IF-THEN-ELSE

USING THE IF STATEMENT TO FILTER DATA

Subsetting IF with Retention
        The IF statement is used in this case to select out observations to keep in a dataset if they meet
the specified condition.

EXAMPLE 1
               DATA PARTIAL;
                    INFILE 'A:\EXP.DAT';
                    INPUT SOIL $ TRT COUNT1 COUNT2;

                         IF SOIL = 'A';
Result:
Dataset Partial
Return to TOP ; Return to Outline

Subsetting IF with Deletion
        Anoher way to select out data from a dataset is through deletion. This requires the addition
of the keyword THEN to the IF statement. In The next example data is thrown out of the dataset
when the IF condition is met.

EXAMPLE 2
               DATA PARTIAL;
                    INFILE 'A:\EXP.DAT';
                    INPUT SOIL $ TRT COUNT1 COUNT2;

                         IF SOIL = 'A' THEN DELETE;
Result:
Dataset Partial
Return to TOP ; Return to Outline

       Sometimes multiple IF statements can be speeded up by using the ELSE clause. This is only
applicable in certain conditions when one IF statement precludes the others.

EXAMPLE 3 - Bad Form
          DATA EXP1;
               INFILE 'A:\EXP.DAT';
               INPUT SOIL $ TRT COUNT1 COUNT2;

               IF TRT = 1 THEN NEW = COUNT1 + 5;
               IF TRT = 2 THEN NEW = COUNT1 + 10;
               IF TRT = 3 THEN NEW = COUNT1 + 15;
               IF TRT = 4 THEN NEW = COUNT1 + 20;


EXAMPLE 3 - Good Form
          DATA EXP1;
               INFILE 'A:\EXP.DAT';
               INPUT SOIL $ TRT COUNT1 COUNT2;
               IF TRT = 1 THEN NEW = COUNT1 + 5;
               ELSE IF TRT = 2 THEN NEW = COUNT1 + 10;
               ELSE IF TRT = 3 THEN NEW = COUNT1 + 15;
               ELSE IF TRT = 4 THEN NEW = COUNT1 + 20;
        In this case the second form is desirable because once TRT has been identified, it is not
necessary to continue testing it. The ELSE keyword causes SAS to skip those statements once
the IF condition has been met.

The ELSE clause is not always appropriate however.

EXAMPLE 4
               DATA EXP1;
                    INFILE 'A:\EXP.DAT';
                    INPUT SOIL $ TRT COUNT1 COUNT2;
                    IF TRT = 1 THEN NEW = COUNT1 + 5;
                    IF SOIL = 'B' THEN TOTAL = COUNT1 + COUNT2;
                    IF SOIL = 'A' AND TRT = 3 THEN DELETE;
                    IF COUNT1 = 0 THEN COUNT1 = COUNT1 + .5;

The use of ELSE in this case would not give the desired results because when one IF is true it
does not preclude the possibility of the others.

Return to TOP ; Return to Outline