For this week Friday’s Function is a utility to check the availability of required columns.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Missing Columns = Function({dt,lstColNames},{Default Local}, lstNames = dt << Get Column Names(string); lstMissingCols = {}; For (i=1,i<=NItems(lstColNames),i++, colName = lstColNames[i]; pos = Loc(lstNames,colName); If (NRows(pos)==0, InsertInto(lstMissingCols,colName) ) ); // return lstMissingCols ); |
When we create a graph of Y versus X, we assume that the X and Y columns exist. The same is true when we join data and select specific columns. Often it is reasonable to just assume that these columns exist, but sometimes that assumption needs to be verified.
It’s quite common for me to assume that the columns exist, but make that assumption explicit with an assertion:
1 2 3 4 |
lstMissing = Missing Columns(dt,"X","Y"); Assert(NItems(lstMissing)==0, "One or more required columns are missing" ); |
Here is a function that will check if a column is missing and return 1 (missing) or 0 (it exists).
calling convention:
b = colmissing(“colname” [,dt])
or
b = colmissing(dt,”colname”)
I recently modified it so that the inputs could be in either order, as I was often getting it wrong.
b is either 1, 0, or . (bad input)
colmissing = function({colstr
,dtf=””
}
,{Default Local}
,
// check if inputs reversed
if(type(colstr)==”Table” & type(dtf)==”String”,
_temp = dtf;
dtf = colstr;
colstr = _temp;
);
colmissing=.;
if(type(colstr)==”String”,
if(dtf==””,
colmissing = is missing(is scriptable(try(column(colstr))))
,
if(type(dtf)==”Table”,
colmissing = is missing(is scriptable(try(column(dtf,colstr))))
)
)
);
return(colmissing);
);
A complementary function colexists() can now also be defined:
colexists = function({colstr
,dt=””
}
,{Default Local}
,
colexists=!colmissing(colstr,dt);
eval(colexists);
);
The output is 1 if the column exists, 0 if it doesn’t.