Solved
Not applicable
Posts: 0

# OR & AND operators in IF statement

I have a dataset which is created using datastep as shown below.
data sample;
input x y \$;
datalines;
12 as
15 24
14 aq
16 26
10 15
;
run;

I want the output dataset to be
x y
15 24
16 26
10 15
i.e. subsetting the obeservation where y should have only numeric values.

When I use the SAS code,

data sample1;
set sample;
if y ne 'as' or y ne 'aq';
run;
I'm not getting the desired output instead I have all the data points.

But the desired output is obtained when the following SAS code is used.

data sample1;
set sample;
if y ne 'as' and y ne 'aq';
run;

Usually the generic understanding is whenever we don't want either 'as' or 'aq', we can use OR operator in IF statement. But in the given code it works well using AND operator. Can anyone give the explanation on how does SAS work when these OR & AND operators are used in the IF statement?

-Suresh.

Accepted Solutions
Solution
‎08-30-2017 11:02 AM
Frequent Contributor
Posts: 139

## Re: OR & AND operators in IF statement

Let's go through the logic of your subsetting if statement.

The first record x=12, y=as
Your logic: if y ne 'as' or y ne 'aq';

y ne 'as', so that is false
y ne 'aq', so that is true

With an OR statement any true resolves to true, hence false or true will resolve to true. With an AND both statements need to be true for it to resolve to true, which is why the AND works and the or does not

BTW: SAS has a function called NOTDIGIT which searches a character string for any character that is not a digit and returns the first position at which that character is found

* For Example;
data sample2;
set sample;
num_check=notdigit(strip(y));
run;

data what_i_want;
set sample2;
if num_check then delete;
run;

All Replies
Solution
‎08-30-2017 11:02 AM
Frequent Contributor
Posts: 139

## Re: OR & AND operators in IF statement

Let's go through the logic of your subsetting if statement.

The first record x=12, y=as
Your logic: if y ne 'as' or y ne 'aq';

y ne 'as', so that is false
y ne 'aq', so that is true

With an OR statement any true resolves to true, hence false or true will resolve to true. With an AND both statements need to be true for it to resolve to true, which is why the AND works and the or does not

BTW: SAS has a function called NOTDIGIT which searches a character string for any character that is not a digit and returns the first position at which that character is found

* For Example;
data sample2;
set sample;
num_check=notdigit(strip(y));
run;

data what_i_want;
set sample2;
if num_check then delete;
run;
Not applicable
Posts: 0

## Re: OR & AND operators in IF statement

Hi Darrylovia,

I understood the concept from your nice explanation.

Regards,
Suresh.
Not applicable
Posts: 0