SAS tips & tricks #1 – The VARNUM function

A couple of well known ways to tell whether a variable is present in a dataset  include using a PROC CONTENTS or by referring to the SASHELP.VCOLUMN Dictionary Table, a perhaps lesser known approach is to utilise the VARNUM function.

The VARNUM function returns the number of a variable’s position within a dataset, or 0 if a variable is not present in a dataset. This value can then be used to control subsequent processing steps, for example,  only executing steps if a particular variable is present in a given dataset.

The function is used in combination with the OPEN function as shown below.

In this example we test to see whether the variable HEIGHT exists in the SASHELP.CLASS dataset. The variable is the fourth column within the dataset and so the function returns the value 4. In our example we’ve assigned this value to the macro variable HEIGHT_EXIST, so that it is readily available in subsequent steps.

DATA _null_;
  dsid=OPEN("sashelp.class");
  CALL SYMPUTX("height_exist",VARNUM(dsid,"height"));
RUN;

The VARNUM function can also be used in combination with other functions, for example VARTYPE and VARLABEL to gain additional information about the attributes of a variable. 

See how in our next SAS Tips & Tricks blog.

Leave your comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>