Monday, April 6, 2009

How to Check, if the variable exists in the SAS dataset or not

How to check if a variable exist or not:

In SAS sometimes, we need to check whether the variable is exist in the dataset or not, we usually run the proc contents program and physically check if the variable exist in the dataset or not.

If we want to check it programmatically, then use the following code....

Sample dataset:

data old;
input ID SCORE1 SCORE2 SCORE3 SCORE4 SCORE5 SCORE6;
cards;
24 100 97 99 100 85 85
28 98 87 98 100 44 90
60 100 97 69 100 100 100
65 100 98 100 93 90 100
70 99 97 100 100 95 100
40 97 99 98 49 100 95
190 100 99 97 100 100 90
196 100 100 99 100 100 100
210 98 85 88 90 80 95 100
;
run;

data _null_;
dset=open('old');
call symput ('chk',varnum(dset,'SCORE4'));
run;


%put &chk;
RESULT:5

Here I have used both OPEN and VARNUM functions in the program to check if SCORE4 variable exists in a 'OLD' dataset.

The OPEN function opens a SAS data set and the VARNUM function, which returns the variable's position in the data set.

If the variable does not exist then VARNUM returns to 0. and if the result is GT 0 then the variable is exist in the dataset.

In this case, the variable SCORE4 location is column 5, so the value for macrovariable CHK will be 5.

4 comments:

Anonymous said...

Once we know if the specific var exists, we need to know the type of it. So, just use the VARTYPE function to get "N" for numeric or "C" or char to the involved variable!

Anonymous said...

You forgot to use the close function at the end of the data _null_step, leaving this dataset open that could cause issues later in the program if you wish to write to the dataset 'old'.

There is also the open code version (uncompiled),
%let dsid = %sysfunc(open(old));
%let chk = %sysfunc(varnum(&dsid, SCORE4));
%let rc = %sysfunc(close(&dsid));
%put &chk;

Anonymous said...

Thank you for posting this SAS code--I found both examples helpful.

Unknown said...

Hi.....
Can you tell me how to check whether an array exist in a dataset or not using sas....

Post a Comment

ShareThis