Andreas Wittberg
Andreas Wittberg

Reputation: 3

sas macro string-comparison does not equate in the same way

This macro string-comparison works in misterious ways for me. The obvious to me would be that the result of %test1(intotest) and %test2(intotest) are equal.

%macro test1(intotest=);
    %str(&intotest) = %str("b");
%mend;

%macro test2(intotest);
    %if %str(&intotest) = %str("b") %then
        1;
    %else 0;
%mend EAF;

data datatable;
    fromtable = 'b';
    test1 = %test1(intotest=fromtable);
    test2 = %test2(intotest=fromtable);
run;

The output is fromtable=b,test1=1,test2=0

How would I rewrite %test2() so that it gives the same result as %test1() and still use the information in the datatable as input?

Upvotes: 0

Views: 2864

Answers (3)

Tom
Tom

Reputation: 51566

The first macro is generating SAS code (including an unwanted extra semi-colon) and the second one is just generating a single word that is either 0 or 1. Turn on the MPRINT option and the difference will be obvious in the SAS log.

 67         data datatable;
 68             fromtable = 'b';
 69             test1 = %test1(intotest=fromtable);
 MPRINT(TEST1):   fromtable = "b";
 70             test2 = %test2(intotest=fromtable);
 MPRINT(TEST2):   0
 71         run;

Upvotes: 1

Quentin
Quentin

Reputation: 6378

The SAS language is designed to process data in data sets (and other sources). The macro language is designed to process text and generate SAS language code.

In your first example, you are successfully using the macro language to generate SAS code fromtable = "b"; and then that SAS code evaluates (for each record) where the data value of the dataset variable fromtable is equal to the literal value b. As an aside, you don't need the %str() function.

In the second example you are trying (hoping) to use the macro language to process data stored in a data step variable. The macro language does not process data step data. [There are some exceptions, but I do not think they would help your understanding.] As written, the macro language is comparing the text string fromtable to the text string "b" (note that string is three characters long, because in the macro language quotation marks are part of the value). The macro language does not know there is a data step variable named fromtable. It does not even know that there are such things as data steps, data sets, and data set variables. Because the text string fromtable is not equal to the text string "b", your macro returns 0.

Upvotes: 3

Robert Soszyński
Robert Soszyński

Reputation: 1188

Your code is equal to this data step, after running macros:

data datatable;
    fromtable = 'b';
    test1 = fromtable = "b";;
    test2 = 0;
run;

Upvotes: 2

Related Questions