BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Francy
Calcite | Level 5

Hi,

i have a dataset like this: 

var1var2var3var4x
  L0 0
U   1
 SI  0
150  1
   1M0

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. 

1 ACCEPTED SOLUTION

Accepted Solutions
Francy
Calcite | Level 5
Great!
Thank you for the code Tom

View solution in original post

2 REPLIES 2
Tom
Super User Tom
Super User

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.

Francy
Calcite | Level 5
Great!
Thank you for the code Tom

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 919 views
  • 4 likes
  • 2 in conversation