Column Expressions: Loop over all columns and create collection

Hi there,

I familiarized with the Column Expressions node and wonder how the Collection option actually works. I.e. I want to loop over all columns like so. It does work but only the last result is given back:

for(let i = 0 ; i < columnNames().length; i++) {
    join(columnNames()[i], "=", substr(column(i), 0, 5))
}

In addition, when attempting to create a collection, I get a strange error despite only having strings present:

ERROR Column Expressions   0:2        Execute failed: An error occurred in script 1:
Error occurred during the conversion of the result '@message=96.35' to 'List':
java.lang.String cannot be cast to [Ljava.lang.Object;

Thanks in advance
Mike

Hi Mike,
Your join() line is an expression returning a string for a single column and since the Column Expression always returns the value of the last expression, you only get the result for the last column. Instead, you need to collect your strings in an array. Here we have to use a workaround because for some reason it is not allowed to create an empty array. I will open a ticket for that.

var output = arrayCreate("");
output = arrayRemove(output, 0);
for(let i = 0 ; i < columnNames().length; i++) {
    output = arrayAdd(output, join(columnNames()[i], "=", substr(column(i), 0, 5)));
}
output

I first create an array with a dummy element because it is not allowed to pass nothing to arrayCreate. Then I remove the element again. Now I go through the columns and add each new string to the output array. Finally I just put “output” so it is the last expression and is returned from the node. The checkbox in the “Collection” column at the top must be checked so KNIME recognizes that I want to create a collection column.
Kind regards,
Alexander

3 Likes

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