Hi everybody,
I have a list containing numbers and I would like to transform them into characters. Is there a way to do that without using a loop? I was not able to find the proper function.
Thanks for your help!
New in JMP 16 is the For Each() function which iterates over a container – list, matrix, or associative array – to perform an operation on each element.
Here is an example to show how to use it to convert your list of numbers to a list of character strings.
Names Default To Here( 1 ); theList = {7, 8, 9}; For Each( {value, index}, theList, theList[index] = Char( value ) );
Here is a little script that creates a function that does what you want. You can either define and use the function in your code, or use the 4 statements in open code to do the conversion.
Names Default To Here( 1 ); theList = {7,8,9}; NumListToChar = Function( {myList}, {defaultlocal}, dtx = New Table( "x", New Column( "y", values( myList ) ), private ); dtx:y << data type( character ); myList = dtx:y << get values; Close( dtx, nosave ); Return( myList ); ); theList = NumListToChar( theList );
Thanks for your answer @txnelson it is indeed what I was looking for.
I just wonder what is the faster between a loop and a function which involves table creation. Any idea?
Thanks @Jeff_Perkinson !
I did some simulations just by curiosity to compare the execution time of each solution and it seems that the for each function is on average the fastest one!
So I am gonna pick that one although the function of @txnelson also works very well.
Thanks to both of you
Here's a quick timing program for the three methods, for loop, for each, and custom function using data table.
Names Default To Here( 1 ); listsize=1000000; theList = As List( J( listsize, 1, Random Integer( 100 ) ) ); NumListToChar = Function( {myList}, {defaultlocal}, dtx = New Table( "x", New Column( "y", values( myList ) ), private ); dtx:y << data type( character ); myList = dtx:y << get values; Close( dtx, nosave ); Return( myList ); ); start = HP Time(); For Each( {value, index}, theList, theList[index] = Char( value ) ); foreachloop = HP Time() - start; theList = As List( J( listsize, 1, Random Integer( 100 ) ) ); start = HP Time(); theList = NumListToChar( theList ); customfunction = HP Time() - start; theList = As List( J( listsize, 1, Random Integer( 100 ) ) ); start = HP Time(); For( i = 1, i <= N Items( theList ), i++, theList[i] = Char( theList[i] ) ); forloop = HP Time() - start; show(foreachloop, customfunction, forloop);
For me with the listsize shown above the results are very similar between the three methods:
foreachloop = 1106974; customfunction = 1077862; forloop = 1400643;
There's also Transform Each, which appears to be a little faster than For Each here.
theList = Transform Each( {value}, theList, Char( value ) );