Saturday, 19 July 2014

How can I put a value from a data file to a Macro Variable?

We can use the SYMPUT function to get information from a data file to a SAS Macro variable.  Consider the example below.  We have a data file test and we have used proc means to save the mean of x to xbar in a new data file named testmean.
data test;
  input x ;
cards;
100
200
300
;
run;

proc means data=test;
  var x;
  output out=testmean mean=xbar;
run;
We would like to get the value of xbar into a macro variable to be used elsewhere.  Below, we use the symput command to put the value of xbar into a macro variable called xbarmac. At the end of the data step we use %put to display this value (to check that it worked) and then in test2 we can use this macro variable to create a mean-centered variable.
data _null_;
  set testmean;
  call symput("xbarmac",xbar);
run;

%put mean of x is &xbarmac;

data test2;
  set test;
  xcent = x - &xbarmac;
run;

proc print data=test2;
run;
Below is the part of the log that shows the value of the macro variable.
                       %put mean of X is &xbarmac;
mean of X is          200
And below we see the output of proc print, and indeed xcent contains x minus the mean of x.
Obs     x     xcent
1     100     -100
2     200       0
3          300           100