Subscribe Bookmark



Mar 21, 2013

JSL Set Operations

A question about using sets of column names. You can use JSL's associative arrays to perform set operations. The methods <<Intersect, <<Remove, and <<Insert do the work.

// make three sets
rgb = associativearray({"red","green","blue"});
cmy = associativearray({"cyan","magenta","yellow"});
bw = associativearray({"black","white"});
// join them together
all = rgb;
show(all<<getkeys); // {"black", "blue", "cyan", "green", "magenta", "red", "white", "yellow"}
// take two from set
two = associativearray({"magenta","red"});
show(all<<getkeys); //{"black", "blue", "cyan", "green", "white", "yellow"}
// find common colors
rainbow = associativearray({"orange","cyan","green","red","blue"});
show(all<<getkeys); // {"blue", "cyan", "green"}

The question was posed in terms of sets of column names, and this example uses the associative array set operation <<remove to get the difference between the set of all columns and the set of columns containing the letter "i".


// keep only the columns with an "i" in the name

dt = Open( "$SAMPLE_DATA/Big" );
allnames = dt << getcolumnnames( "string" );

inames = {};
For( i = 1, i <= N Items( allnames ), i++,
	If( Contains( allnames[i], "i" ),
		Insert Into( inames, allnames[i] )

allset = Associative Array( allnames ); // {"name", "age", "sex", "height", "weight"}
iset = Associative Array( inames ); // {"height", "weight"}

allset << Remove( iset ); // the "not i" set...
notinames = allset<<getkeys; // {"age", "name", "sex"}

For( i = 1, i <= N Items( notinames ), i++,
	dt:(notinames[i]) << Set Selected( 1 )
dt << Delete Columns(); // only the "i" names remain


1 Comment
Community Trekker

This is very nice.  I hadn't thought to use associative arrays like this.  I've had situations in the past where I've used a list of object references, and I wanted search through the list to eliminate objects that met certain conditions.  Using list operations was pretty slow and the control logic was complicated.  I can see how this would make it much easier.  I'm copying and pasting your example code to add to my "JSL collection" for future reference!

Article Tags