I was running the following code given in the sas documentation.
data info; input x; if 1<=x<=5 then go to add; put x=; add: sumx+x; datalines; 7 6 323 ;
I think " if condition is false", why it is executing the statment in the add label.
Whereas in the context of the %goto, it executes %goto label when it is true only (code below- http://www.lexjansen.com/nesug/nesug03/cc/cc016.pdf).
%MACRO READ;
%DO I = 1 %TO 4;
%IF &I = 3 %THEN %GOTO OUT;
DATA CTY_&I;
INFILE "D:\NESUG\CTY_&I";
INPUT ID F96 F97 F98;
RUN;
%OUT: %END;
%MEND READ;
%READ
I am really confused now. I thought %goto was just macro counterpart of goto.
Your data step example ADD is just a label. Since you do not have any way of not executing it then you get the result everytime. The code below is the same as yours.
data info;
input x;
if 1<=x<=5 then go to add;
put x=;
add:
sumx+x;
datalines;
7
6
323
;
If you do not want the sumx+x executed for every step the Return is used with Goto
data info;
input x;
if 1<=x<=5 then go to add;
put x=;
return;
/* SUM statement not executed */
/* if x<1 or x>5 */
add: sumx+x;
datalines;
7
6
323
;
Your data step example ADD is just a label. Since you do not have any way of not executing it then you get the result everytime. The code below is the same as yours.
data info;
input x;
if 1<=x<=5 then go to add;
put x=;
add:
sumx+x;
datalines;
7
6
323
;
If you do not want the sumx+x executed for every step the Return is used with Goto
data info;
input x;
if 1<=x<=5 then go to add;
put x=;
return;
/* SUM statement not executed */
/* if x<1 or x>5 */
add: sumx+x;
datalines;
7
6
323
;
Hi,
BallardW is correct in the data step code posted and his explanation of the 'return;' statement.
To explain why %GOTO behaved as it did, consider what is after the %IF in your code: it is a complete datastep with a RUN; which terminates that group of SAS statements. In that respect it is similar to "return;" (not strictly true, but close enough). Remember also that macro language is simply a mechanism for generating SAS code - it has its own execution logic that passes the generated code for SAS to compile and execute.
So the effect of your macro conditional is to either generate a whole data step (when the condition is false), or to skip that by jumping to the %END statement, labelled with the name OUT.
BTW, on a coding style point, I recommend *always* having an explicit "else..." along with "if...then..." - too often I've had to debug someone else's code that has misbehaved because the author didn't do that!
Regards
Steve M.
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.