Hello,
I am working on a few else if conditions to understand how else if works on different variables:
In the below example 'cl' doesn't get overwritten to 2 which means once the if condition is successful on a record it is not evaluating that record again.
data cls;
set sashelp.class;
if sex="M" then cl=1;
else if age=14 then cl=2;
run;
However, in the below example where I am working on same record and running else if on two different variables, it is getting overwritten. I don't understand why it is reading the same record again in else if (it did not in the above example).
data chk;
set cm1;
if (trtsdtm <= aendtm) then cmfl= 'Y';
else if (trtsdt <= aendt) then cmfl= 'Y';
run;
@Tommer wrote:
For the sashelp.class, it did not seem to do the same thing---cl is populated as 1 not 2 although the second condition is true as well.
That's how IF THEN ELSE works ... when the IF is true on a given record, the ELSE doesn't get applied to that record.
I don't understand why it is reading the same record again in else if (it did not in the above example).
A SAS data step works on all records. It applies all the code to all records (unless there is some code to force it to advance to another record).
So, this section of code comprising two lines, one beginning with IF and the nnext one beginning with ELSE, are executed on the current record,
if (trtsdtm <= aendtm) then cmfl= 'Y';
else if (trtsdt <= aendt) then cmfl= 'Y';
as there is nothing in your code to tell it to move on the the next record between records. If either or both conditions are true, you get CMFL='Y'.
The code you show working on SASHELP.CLASS does the same thing. The block of code comprising of an IF and an ELSE are run on all records.
@Tommer wrote:
For the sashelp.class, it did not seem to do the same thing---cl is populated as 1 not 2 although the second condition is true as well.
That's how IF THEN ELSE works ... when the IF is true on a given record, the ELSE doesn't get applied to that record.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.