Search code examples
sassas-macro

Dynamic n in function LAG<n> (variable) SAS


do you know how to use n in function LAGn(variable) that refer to another macro variable in the program-> max in my case?

data example1;                                                 
input value;                                                  
datalines;                                                    
1.0                                                          
3.0                                                            
1.0                                                          
1.0                                                          
4.0                                                           
1.0                                                          
1.0                                                          
2.0                                                          
4.0                                                            
2.0                                                          
;       
proc means data=example1 max;
output out=example11 max=max;
run; 
data example1;  
%let n = max;  
lagval=lag&n.(value);                                            
run;                                                          

proc print data=example1;                                                   
run;

Thank you in advance! Wiola


Solution

  • Is this what you're trying to do?

    data example1;                                                 
    input value;                                                  
    datalines;                                                    
    1.0                                                          
    3.0                                                            
    1.0                                                          
    1.0                                                          
    4.0                                                           
    1.0                                                          
    1.0                                                          
    2.0                                                          
    4.0                                                            
    2.0                                                          
    ;       
    
    proc sql;
      select max(value) format = 1. into :n
      from example1;
    quit;
    
    data example1;
      set example1;
      lagval=lag&n(value);                                            
    run;     
    

    The format = 1. bit makes sure that the macro variable generated by proc sql doesn't contain any leading or trailing spaces that would mess up the subsequent data step code.