Can I use %let statement conditionally outside of macro? Do I always have to define macro first and put %let inside if I want to use this with a certain condition?
For example, can I modify the second sentence so that it only works when x is equal to one? Then, the second sentence wouldn't work if 2 is given to x.
%let x= 1;
%let y= &x;
If your SAS version/release doesn't yet allow open code macro statements mentioned by @Astounding, you can do:
data _null_ ;
if "&x" = "1" then call symputx ("y", "1") ;
run ;
but it's hardly better than using a macro. Or if the macro variable Y already exists, you can do a simpler:
%let y = %sysfunc (ifc (&x=1, 1, &y)) ;
If Y doesn't yet exist and X is not 1, it will result in a recursive error. But if you want Y to become 1 if X=1 and null otherwise regardless of whether Y already exists or not and/or its existing value, you can do:
%let y = %sysfunc (ifc (&x=1, 1,)) ;
Kind regards
Paul D.
The capability you are asking about depends on the release of SAS that you are using. In recent updates to the software, you would be allowed to do this without having to define a macro:
%let x = 1;
%if &x=1 %then %let y = &x;
As of SAS 9.4M5 released there is limited support for %IF/%THEN statements in open code. You must use %DO/%END block.
%let x= 1;
%if &x=1 %then %do;
%let y= &x;
%end;
You can always use a data step for creating a macro variable.
data _null_;
if symget('x')='1' then call symputx('y',symget('x'));
run;
You can use the IFN (or IFC) function with %SYSFUNC(), but then you would need to know what you want to set Y to when X is not 1.
If your SAS version/release doesn't yet allow open code macro statements mentioned by @Astounding, you can do:
data _null_ ;
if "&x" = "1" then call symputx ("y", "1") ;
run ;
but it's hardly better than using a macro. Or if the macro variable Y already exists, you can do a simpler:
%let y = %sysfunc (ifc (&x=1, 1, &y)) ;
If Y doesn't yet exist and X is not 1, it will result in a recursive error. But if you want Y to become 1 if X=1 and null otherwise regardless of whether Y already exists or not and/or its existing value, you can do:
%let y = %sysfunc (ifc (&x=1, 1,)) ;
Kind regards
Paul D.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.