Conditionally set a %let statement SAS

162 views Asked by At

I was hoping someone could help with %if %then statements in SAS.

I want to conditionally set a macro variable so I was trying to do it this way:

%if &stress_test. = "Y" %then %let CURR_BOE = &BOE_ST.;
%if &stress_test. = "N" %then %let CURR_BOE = 0.0525;

Where &stress_test. is a macro variable already set. And &BOE_ST is a macro variable already set.

2

There are 2 answers

1
PeterClemmensen On BEST ANSWER

When you do %if-%then-%else Macro logic in open code, there are restrictions. See the blog post Using %IF-%THEN-%ELSE in SAS programs.

  1. The %if-%then must be followed by a %do-%end block for the statements that you want to conditionally execute.
  2. Nesting is not allowed.

Since you have to consecutive %if statements in your code with no %do block following it, SAS interprets this as nesting and both restrictions are violated.

This gives an error:

%let stress_test = N;

%if &stress_test. = Y %then %let CURR_BOE = 1;
%if &stress_test. = N %then %let CURR_BOE = 2;

%put &=CURR_BOE.;

This does not give an error

%let stress_test = N;

%if &stress_test. = Y %then %do;
   %let CURR_BOE = 1;
%end;
%else %do;
   %let CURR_BOE = 2;
%end;

%put &=CURR_BOE.;

Also, you could just wrap the whole thing into a macro and call that. Then you do not have the two restrictions mentioned.

%macro m;

%let stress_test = N;

%if &stress_test. = Y %then %let CURR_BOE = 1;
%if &stress_test. = N %then %let CURR_BOE = 2;

%put &=CURR_BOE.;

%mend m;

%m
2
PeterClemmensen On

Your code looks fine, but I suspect your problem is not realizing that the SAS macro language is a text language. My guess is that the &stress_test. macro variable takes some value Y or N, NOT "Y" or "N". There is a difference.

Therefore, I think all you need to do is this.

%if &stress_test. = Y %then %let CURR_BOE = &BOE_ST.;
%if &stress_test. = N %then %let CURR_BOE = 0.0525;