Skip to Main Content

How can I put a value from a data file to a macro variable? | SAS FAQ

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.

404  %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