Monday, 12 October 2015

ALTERNATIVE TO IF -THEN ELSE

Most programmers will have used the IF THEN ELSE statements when working with conditional processing. Assigning one value for when the condition is true, and another value for when the condition is false. In these situations you can reduce lines of code by instead using the functions IFC and IFN.

These functions can both create a new variable with assigned values based on whether a condition is true or false. IFC will create a character variable and IFN will create a numeric variable. 


Below are standard templates for using IF THEN ELSE to create numeric/character variables, along with their counterpart in IFN and IFC:

*Standard IF THEN ELSE code (numeric);
if condition then variable=value1;
else variable=value2;
 *Equivalent IFN code;
variable=ifn(condition,value1,value2);
 *Standard IF THEN ELSE code (character);
if condition thenvariable='value1';
else variable='value2';
 *Equivalent IFC code;
variable=ifc(condition, 'value1' ,'value2') ;

You can see that IFN and IFC effectively cut down and rearrange the keywords from IF THEN ELSE code and change it into just one compact line of code.

For example both the following sets of code can be used to create the same variable:

if sex='Male' then sexcd=1;
else sexcd=0;


sexcd=ifn(sex='Male',1,0);

table_1


Either code can be used here and will produce the same result. In order to compare processing times I ran equivalent code five times for each method and recorded the average times. These were run within server SAS version 9.1.3 and showed very little difference in average processing times. However the IFN function has the advantage of requiring less code.

These functions are ideal when you wish to create variables with 2 possible values.

No comments:

Post a Comment