WeeklyAlteryxTips#29 How to write an IF statement in an easy-to-understand manner part2

Alteryx

This post is also about function. I will explain how to make the complex IF statement easier to understand.

First

I prepare the simple data.

Suppose that you want to make a combination flag that the field “value1” and “value2” are odd or even number. For that, you can make the statement as follows.

IF Mod([value1], 2)=1 AND [value2]=1 THEN "odd_odd"
ELSEIF Mod([value1], 2)=1 AND [value2]=2 THEN odd_even"
ELSEIF Mod([value1], 2)=0 AND [value2]=1 THEN "even_odd"
ELSEIF Mod([value1], 2)=0 AND [value2]=2 THEN "even_even"
ELSE Null() ENDIF

This shows the result below.

This statement is necessary to consider the value1 and value2 combination, so if the pattern is more complex, it is easy to take mistakes.

Simplified IF statement

In this case, you can make the statement more simple as follows.

IF Mod([value1], 2)=1 THEN "odd"
ELSE "even" ENDIF
+"_"+
IF [value2]=1 THEN "odd"
ELSE "even" ENDIF

This means that you can combine the result of IF statement. You can make the IF statement for value1 and also make the IF statement for value2, and then you can connect those statement results by +(plus) operator. So that statement become very simple.

At this time, those statement was connected as string type, but if the result of the IF statement result are numeric, you can calculate such as addition and subtraction.

More simplified by IIF statement

In this case, the condistions are ery simple, so if you use the IIF statement, it will be more simple.

IIF(Mod([value1], 2)=1, "odd", "even")
+"_"+
IIF([value2]=1, "odd", "even")

It’s quite simple! But, when there are many conditions, IIF statements will be quite complex. I recommend that you only use IIF statement at the simple conditions. For example, suppose that you want to make flag as three conditions, value1 is a multiple of 3, an even number, an odd number.

IIF(Mod([value1], 2)=0, "even", IIF(Mod([value1], 3)=0, "multiple of 3","odd" ))

This is a little confusing to understand because it is nested.

But if you use IF statement, it will be a little simple.

IF Mod([value1], 2)=0 THEN "even"
ELSEIF Mod([value1], 3)=0 THEN "multiple of 3"
ELSE "odd" ENDIF

Conclusion

  • I explained that you can use to calculate the result of IF statement like simple numeric value or string value.
  • When the condisionts are simple, IIF statement will be very simple. But when the conditions are complex, IF statement is easier to understand than IIF statement.

Sample Workflow Download

Contents of the next blog

The next blog post will be about functions.

コメント

タイトルとURLをコピーしました