Test if a variable exists

白昼怎懂夜的黑 提交于 2019-11-27 07:51:26

问题


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;


来源:https://stackoverflow.com/questions/5657117/test-if-a-variable-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!