Hi,
i have a dataset like this:
var1 | var2 | var3 | var4 | x |
L0 | 0 | |||
U | 1 | |||
SI | 0 | |||
1 | 50 | 1 | ||
1M | 0 |
and I would like to generate a code conditional on the data.
This is the code I would like to obtain:
if var3='L0' then x=0;
if var1='U' then x=1;
if var2='SI' then x=0;
if var1='1' and var2='50' then x=1;
if var4='1M' then x=0;
As you can see when a variable is missing, I don't want the condition to contain it while when there is more than one not missing variables I would like a condition containing all not missing variables linked by an "and".
I tried with a data _null_ code without success.
Can you suggest me the code?
Any help is really appreciated.
Thank you very much in advance
F.
A simple REPORT WRITING problem. Where the REPORT you want to write is SAS CODE.
data metadata ;
infile cards dsd dlm='|' truncover;
input (var1-var4) (:$8.) x ;
cards;
| |L0| |0
U| | | |1
|SI| | |0
1|50| | |1
| | |1M|0
;
filename code temp;
data _null_;
file code;
set metadata ;
array var var1-var4 ;
length name $32 sep $3 ;
sep='if';
do index=1 to dim(var);
if not missing(var[index]) then do;
name=vname(var[index]);
put sep name '=' var[index] :$quote. @ ;
sep='and' ;
end;
end;
put 'then ' x= ';' ;
run;
Which will generate code like:
if var3 ="L0" then x=0 ; if var1 ="U" then x=1 ; if var2 ="SI" then x=0 ; if var1 ="1" and var2 ="50" then x=1 ; if var4 ="1M" then x=0 ;
which you could then use in a data step (or anywhere you can use IF/THEN statements) by using %INCLUDE.
data want;
set have;
%include code / source2;
run;
Note that the result of that series of IF/THEN statements is that the last one that is satisfied will "WIN". If that is not what you wanted then you might need to re-order the metadata file. Or generate more complex code.
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Select SAS Training centers are offering in-person courses. View upcoming courses for: