SAS9

How to effectively test for a missing value in a SAS macro variable?

Simon 8 Aufrufe

One of the most common confusions when learning the SAS© Macro language is handling missing values. Unlike the Data step where a period (.) represents a missing numeric value, the macro processor treats everything as text.

This article explains how to distinguish a null (empty) macro variable from a macro variable containing a period, and how to perform these tests correctly.

How to effectively test for a missing value in a SAS macro variable? -

The common trap: the period (.) vs. empty

It is crucial to understand the nature of your variable:

  1. Null macro variable: It contains no characters.

    • Example: %let myVar = ;

  2. Macro variable containing a period: It contains the character ".". For the macro processor, it's a character string of length 1, not a missing value.

    • Example: %let myVar = .;

If you test %if &myVar = ., you are literally checking if the variable contains the character "period", not if it is empty.

The most robust method to check if a macro variable is "empty" or "null" is to test its length.

To check if a variable is empty:

1%IF %LENGTH(&maVar) = 0 %THEN %DO;
2 
3%put The variable is empty.;
4 
5%END;
6 

To check if a variable contains a value (non-empty):

This syntax works because in SAS©, any number other than 0 is evaluated as "True".

1%IF %LENGTH(&maVar) %THEN %DO;
2 
3%put The variable contains something (LENGTH > 0).;
4 
5%END;
6 
Warning: If %let a = .;, then %length(&a) is 1. The test above will therefore consider that the variable is not empty.

Method 2: Direct comparison

Another common method is to compare the variable to an empty string.

1%IF &maVar = %THEN %DO;
2 
3%put The variable is empty.;
4 
5%END;
6 
Note: This method is sometimes less readable than using %length, but it is functional.

Common syntax errors to avoid

When writing these conditions, pay attention to the structure of your %if / %then / %else blocks.

The semicolon error after %else

A classic mistake is to place a semicolon immediately after the %else, which terminates the statement prematurely.

Note :
Incorrect:
1/* The semicolon after %else prevents the execution of the next block */
2%IF %LENGTH(&a) %THEN %DO;
3 %put Exists;
4%END;
5%ELSE;
6 %put Does not exist;
Note :
Correct:
1%IF %LENGTH(&a) %THEN %DO;
2 %put Exists;
3%END;
4%ELSE %DO;
5 %put Does not exist;
6%END;
  • The macro language manipulates text.

  • A period (.) is a character, not a missing value in the macro sense.

  • Use %if %length(&var) = 0 to test for a null (empty) value.

  • To delve deeper into the subject of missing and logical values in macros, the works of Chung and King on the subject are solid technical references.