Suppose I allow user to write his own variable calculation macro using a common user interface:
%macro calculate(var_name, var_value);
%* Some user-defined calculation;
%mend calculate;
Then in a data step, I can calculate a new variable using the user-defined macro:
data dataset;
set dataset;
new_var = %calculate('variable1', variable1); * This doesn't work. It just shows my indication.
run;
Where variable1 is a variable in dataset. Here, I want to pass in the variable name and the actual value of the variable. After the calculation, put the value in new_var.
How can I achieve this?
You can make this work, but you are probably writing the macro incorrectly. You have to remember that SAS macros are essentially text preprocessors: they input the code you have written and output code to feed to SAS [1].
So here is a simple “addition” macro:
The macro facility will replace the
%calculatebits with the code generated by the macro, and SAS will actually see the following:You can see it for yourself on the log file with the
options mprintstatementUnfortunately, this will not cover all potential calculations. You might want to look up
PROC FCMPfor a way to generate custom functions/subroutines usable in the DATA step.[1] I know it is more complicated than that, but you can get far thinking like this.