Sum Last 3 Non Zeros in a Row

Here I got 1 table where i got the following
1 5 4 7 8 3 0 7 0 8 0 2

I want to sum only the last 3 values from right to left ignoring the zeros, example it will sum 17.

Is there a way to make this happen?

Hi @Kikemx7 and welcome to the Knime Community.

It would be better if you could show how these look in a table. For example, are these numbers all in 1 cell, separated by a space? Or is each of these numbers in a cell? And it would be better if you also provided different examples, and more importantly, different variations in your examples.

For example, can we have cases where, if we ignore the zeros, you end up with less than 3 values, like this:
1 0 0 0 0 0 0 0 0 2 0 0

What should happen in this case?

Each of the numbers are in a cell.

Examples:
1 3 5 7 8 0 2 7 0 8 0 2 = 17
2 5 0 2 0 0 5 0 0 2 1 4 = 7
0 0 0 2 0 0 0 4 0 0 0 0 = 6 since there is only 2 values
2 0 0 0 0 0 0 0 0 0 0 0 = 2 since there is only 1 value
0 0 0 0 0 0 0 0 0 0 0 0 = 0 since there is no value

Thanks for the confirmation and the sample data @Kikemx7

Here’s one way of doing this:
image

Input (same as your sample data):

Results:

EDIT: Sorry, forgot to provide the workflow. Here it is:

5 Likes

Hello there,

in general I prefer using KNIME nodes and not coding but this one seems well suited to show possibilities of Column Expressions node:

sum = 0
sum_pos = 0

for (let i = 1; i <= numberOfColumns() ; i++) {

if (sum_pos == 3) {break} // leave for loop if already 3 non zero numbers are summed

sum = sum + column(numberOfColumns() - i) // “else” sum

if (column(numberOfColumns() - i) > 0) {sum_pos++} // count non zero numbers
}

sum

Welcome to KNIME Community @Kikemx7!

Br,
Ivan

3 Likes

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