Test if a variable exists

2020-02-07 03:02发布

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

标签: sas exists
4条回答
The star\"
2楼-- · 2020-02-07 03:07

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.

查看更多
走好不送
3楼-- · 2020-02-07 03:07

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;
查看更多
乱世女痞
4楼-- · 2020-02-07 03:10

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;
查看更多
甜甜的少女心
5楼-- · 2020-02-07 03:30
data try2;
    set try;
    var4 = coalesce(var4,.);
run;

(assuming var4 is numeric)

查看更多
登录 后发表回答