How can I execute part of the code without commenting out code? Let's say I have the following code:
data dataset_1;
set dataset_1;
male=0;
if sex=1 then male=1;
run;
data dataset_2;
set dataset_2;
female=0;
if sex=2 then female=1;
run;
I would like to execute only the first data step without commenting out the second data step. It would great if I could have a macro at the very top of the script and if this macro equals to 1 the script would execute on the first data step and if the macro equals to 2 then it would execute both data steps. Is this possible?
That's just because of the %else part. You could, for example, do this:
%macro runit(run1=0, run2=0);
%if &run1 %then %do;
* do run1 stuff ;
%end;
%if &run2 %then %do;
* do run2 stuff ;
%end;
%mend; *runit();
%runit(run1=1, run2=1); * run both ;
%runit(run1=0, run2=1); * run only the 2nd... ;
That's what %if / %then / %else logic is for:
%macro runit(n);
%if &n=1 %then %do;
* do n=1 stuff ;
%end;
%else %if &n=2 %then %do;
* do n=2 stuff ;
%end;
%mend; *runit();
%runit(1)
@quickbluefish how would you adjust your code to either execute only first block or both blocks. Right now it does either first or second block if I understand the code correctly.
That's just because of the %else part. You could, for example, do this:
%macro runit(run1=0, run2=0);
%if &run1 %then %do;
* do run1 stuff ;
%end;
%if &run2 %then %do;
* do run2 stuff ;
%end;
%mend; *runit();
%runit(run1=1, run2=1); * run both ;
%runit(run1=0, run2=1); * run only the 2nd... ;
I am tempted to ask why you are creating the variables male/female at all, but this maybe out of scope.
I don't. It was just an example with some easy code. I usually have only one dummy either female or male.
You can use %IF blocks for that.
And if you keep them very simple you don't even need to define a macro.
Instead just set a macro VARIABLE and have the %IF logic test that macro variables value.
So let's make a simpler/clearer example. Say you want to create either the MALE or the FEMALE dummy variable you could do something like this.
First decide how to parameterize you macro variable. For example you might decide it is named GENDER and should have a value of MALE or FEMALE.
%let gender=MALE;
Then at the point in your code where you make the dummy variable add the %IF logic.
data with_dummy;
set have;
%if %upcase(&gender)=MALE %then %do;
&gender = (sex=1) ;
%end;
%if %upcase(&gender)=FEMALE %then %do;
&gender = (sex=2);
%end;
run;
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.