Test if a variable exists

2020-02-07 03:01发布

问题:

I want to test if a variable exists and if it doesn't, create it.

回答1:

The open()&varnum() functions can be used. Non-zero output from varnum() indicates the variable exists.

data try; 
    input var1 var2 var3;
    datalines;
    7 2 2
    5 5 3
    7 2 7
; 

data try2; 
    set try;
    if _n_ = 1 then do; 
        dsid=open('try'); 
        if varnum(dsid,'var4') = 0 then var4 = .; 
        rc=close(dsid);
    end;
    drop rc dsid;    
run;


回答2:

data try2;
    set try;
    var4 = coalesce(var4,.);
run;

(assuming var4 is numeric)



回答3:

Assign var4 to itself. The assignment will create the variable if it doesn't exist and leave the contents in place if it does.

data try; 
    input var1 var2 var3;
    datalines;
    7 2 2
    5 5 3
    7 2 7
; 

data try2; 
    set try; 
    var4 = var4; 
run;

Just remember that creating var4 this way when it doesn't exist will use the default variable attributes, so you may need to use an explicit attrib statement if you require specific formatting/length etc.



回答4:

This is a very late answer/comment, but this method works for me and is pretty simple (SAS 9.4). In the below example, I used missing numeric and character variables and assigned a value to the missing character variable is missing.

    data try; 
input var1 var2 var3;
datalines;
7 2 2
5 5 3
7 2 7
; 

    data try2; 
length var4 $20;
length var5 8;
set try; 
var4 = var4; 
if var4 = ' ' then var4 = 'Not on Source File';
run;


标签: sas exists