Monday, March 13, 2017

Hack 4.16 Simplifying IF/THEN/ELSE Statements Using the IFC and IFN Functions


SAS Programming Professionals,

Did you know that the IFC and IFN functions allow you to have 1-line IF/THEN/ELSE-like statements? 

The IFC and IFN functions can be handy when you have a single THEN condition and a single ELSE condition and you would like to have an action taken if the test condition results in missing values.

The IFC function returns a character value based on whether or not an expression is true, false, or missing.  The basic form of the function is:

               IFC(logical-expression, value-returned-when-true, value-returned-when-false <,value-returned-when-missing>)

Here is an example:

data class_gender;
set  sashelp.class;

length gender $7;
label gender = "Gender";

gender = ifc(sex="M", "Male  ", "Female", "Unknown");

run;

In the example, we test variable SEX for the value “M”.  If SEX = “M”, the variable GENDER is set to “Male”.  If not, it is set to “Female”.  If SEX contains a missing value, it is set to “Unknown”.

The IFN function returns a numeric value based on whether or not an expression is true, false, or missing.  The basic form of the function is:

               IFN(logical-expression, value-returned-when-true, value-returned-when-false <,value-returned-when-missing>)

Here is an example:

data electric_surcharge;
set  sashelp.electric;

label surcharge = "Surcharge (B)";

surcharge = ifn(year=2005, revenue *.001, revenue * .000025, 0);

run;

In the example, we test the variable YEAR for the numeric value of 2005.  If YEAR = 2005, the variable SURCHARGE is set to REVENUE * .001.  If YEAR does not equal 2005, SURCHARGE is computed to be REVENUE * .000025.  If YEAR contains missing values, SURCHARGE is set to Zero.

You can probably think of dozens of uses for the IFC and IFN functions.  I like to think of these two functions as “IF/THEN/ELSE in a can”.

Best of luck in all your SAS endeavors!

---MMMMIIIIKKKKEEEE
(aka Michael A. Raithel)
Author of the new cult classic for computer programmers:  It Only Hurts When I Hit <ENTER>
Print edition:  http://tinyurl.com/z8bzx2e 
Kindle edition: http://tinyurl.com/zypgqa7 

The hack above is an excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers

No comments:

Post a Comment