DATA Step, Macro, Functions and more

Need help with sas macros

Reply
New Contributor
Posts: 2

Need help with sas macros

Hi Guys,

I have several columns with column names like this:

A B C D E F G.....

what I want to do is to create new columns as A+B,A+C, A+D... and then B+C, B+D, B+E, ...  and C+D, C+E, C+F...

I need to repeat this process for many times. Anyone can give me a hint how to write macro on this?

Thank you.

Respected Advisor
Posts: 3,799

Re: Need help with sas macros

Posted in reply to honeyhoney

I would use PROC SCORE

data score;
   retain _TYPE_ 'SCORE';
  
array _v
  • A B C D
  • /*E F G H I*/;
      
    length _name_ $32;
      
    do _k_ = 1 to dim(_v);
          do _i_ = _k_+1 to dim(_v);
             _name_ = catx('_',vname(_v[_k_]),vname(_v[_i_]));
             do _j_ = 1 to dim(_v);
                if _k_ eq _j_ or _i_ eq _j_ then _v[_j_] = 1;
               
    else _v[_j_] = 0;
               
    end;
            
    output;
            
    end;
         
    end;
      
    drop _k_ _i_ _j_;
       run;
    proc print;
      
    run;


    data test;
       array _v
  • A B C D
  • /*E F G H I*/ (1:4);
       do _n_ = 1 to 10;
         
    do _i_ = 1 to dim(_v);
             _v[_i_] = _v[_i_] * 2;
            
    end;
         
    output;
         
    end;
      
    drop _:;
       run;
    proc score data=test score=score out=scored;
       run;
    proc print;
      
    run;

    2-19-2015 4-37-20 PM.png  


    Missing works as well as zero so the SCORE data can be simplified slightly.
    data score;
       retain _TYPE_ 'SCORE';
      
    array _v
  • A B C D
  • /*E F G H I*/;
      
    length _name_ $32;
      
    do _k_ = 1 to dim(_v);
          _v[_k_] = 1;
         
    do _i_ = _k_+1 to dim(_v);
             _name_ = catx('_',vname(_v[_k_]),vname(_v[_i_]));
             _v[_i_] = 1;
            
    output;
            
    call missing(_v[_i_]);
             end;
         
    call missing(_v[_k_]);
          end;
      
    drop _k_ _i_;
       run;

    Message was edited by: data _null_

    Super User
    Super User
    Posts: 7,047

    Re: Need help with sas macros

    Posted in reply to honeyhoney

    You might need macro code (or at least some method to generate macro variables) to make up meaningful names, but to make the sums you can do with straight SAS code.

    %let names=a b c d e ;

    %let n=%sysfunc(countw(&names));

    data want;

    set have ;

    array single (&n) &names ;

    array double (&n,&n) ;

    do i=1 to &n ; do j=i+1 to &n ;

       double(&i,&j) = single(&i) + single(&j);

    end;

    run;

    New Contributor
    Posts: 2

    Re: Need help with sas macros

    Thanks!

    Ask a Question
    Discussion stats
    • 3 replies
    • 248 views
    • 0 likes
    • 3 in conversation