开发者

Test if a variable exists

I want to test if a variable exists and if it doesn't, create i开发者_C百科t.


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;


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

(assuming var4 is numeric)


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜