Hi, I would like to know what is the correct way to write or in other words use AND OR NOT operators in SAS?
Let's us suppose we have 3 variables with names A B C in a dataset
/*which way of syntax is correct*?*/
if missing(a) or missing(b) and missing(c) then..... is this correct? or
if (missing(a) or missing(b)) and missing(c) then......is is correct, meaning with the parenthesis?
another condition:
if missing(a) and missing(b) and missing(c) then......is this correct? or
if (missing(a) and missing(b)) and missing(c) then...is is correct, meaning with the parenthesis?
Please clarify the need for parenthesis. Thanks
Try it and see.
%let tests=
a and b or c
|(a and b) or c
|a and (b or c)
|a or b and c
|(a or b) and c
|a or (b and c)
;
%macro xx ;
data xx;
do a=0,1 ;
do b=0,1;
do c=0,1;
put (a b c) (=);
%do i=1 %to %sysfunc(countw(&tests,|));
testn=&i;
test= "%scan(&tests,&i,|)";
val= %scan(&tests,&i,|);
put (testn test val) (=);
output;
%end;
end; end; end;
run;
%mend xx;
%xx;
You need to define CORRECT.
All will work but may generate different results so it depends on what you're looking for.
I am just trying to learn and understand by asking how the condition is checked with and without parentheses and how the results differ. Thanks
There is also documentation on the Order of Operations in Compound Expressions:
Try it and see.
%let tests=
a and b or c
|(a and b) or c
|a and (b or c)
|a or b and c
|(a or b) and c
|a or (b and c)
;
%macro xx ;
data xx;
do a=0,1 ;
do b=0,1;
do c=0,1;
put (a b c) (=);
%do i=1 %to %sysfunc(countw(&tests,|));
testn=&i;
test= "%scan(&tests,&i,|)";
val= %scan(&tests,&i,|);
put (testn test val) (=);
output;
%end;
end; end; end;
run;
%mend xx;
%xx;
Beautiful. That clears all my doubts in my brain. Thanks Tom!
Personally, I make it a habit to use parentheses to clarify the order that I want for the evaluation, even if it matches the order without parentheses. This is for two reasons; first, different languages use different rules, and it's easy to make a mistake, and second, when someone else is looking at the code, they may not know the correct rules, and may mistake what the code is doing.
On the other hand, I don't see any downside to using extra parentheses to make is explicitly clear.
Tom
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.