# Best Node for nested if-then logic?

Hi. I have some complex coding to do that seems best tackled using nested if-then statements.

For example, if I am coding column A, the logic might look like this:

IF X=1 OR X=2 OR X=3 THEN
IF Y=1 or Y=2 THEN
A=1
ELSE IF Y=3 OR Y=4
A=2
ELSE
A=9
END IF
ELSE IF X=4
IF Z=1
A=1
ELSE IF Z=2 OR Z=3
A=4
END IF
END IF

This is a simplified example, what I need to do will often go four nests deep.
All of the variables I am dealing with are numeric.
I know how to do this in Excel and SPSS, but not sure the best way in Knime.

I have seen Java Snippet mentioned. Is this in fact my best bet? I am not too familiar with Java, but this is something I will need to be doing often, so if I need to spend some time learning it, Iâ€™ll do so.

Iâ€™ve used Rule Engine a lot for simpler logic, but I do not see how to do nested logic in that environmentâ€¦ am I missing something?

Thanks for any help!.

EDIT: Looks like I need to figure out how to indent, I see my example is pretty hard to read. Iâ€™ll try to figure that out.

I think the Column Expressions, Rule Engine, and Java Snippet nodes will all be able to do this.

This thread has some tips

3 Likes

Thanks!

So it looks to me like Column Expressions would still entail writing this in Java? I think I mostly figured it out, though I am struggling a bit with how Java is handling missing values. Seems if a value I am checking is missing, it just skips the entire if/then logic.

I have not seen anything indicating how one would set up nested logic in Rule Engine. Can you point me to any examples of how to do this? As far as I can tell, after you check for a condition being true, the only option is to assign a value (rather than start another conditional statement).

Use IsMissing() function to apply logic for missing values.

This might be too advanced, but you could use a python script within the KNIME workflow. Read your data in as a pandas dataframe and write the function.

KNIME and python:
https://docs.knime.com/2018-12/python_installation_guide/index.html

IF/Else in pandas df:
https://datatofish.com/if-condition-in-pandas-dataframe/

Thanks for the help.

I got it done using Java Snippet (simple).
For the missing values I checked the â€śInsert Missing as Nullâ€ť box, and then checked for null using

if (\$column\$ != null)

Works as expected.

2 Likes

Hi there @Kapusta,

Br,
Ivan

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.