How can I execute a piece of macro for each observation in the sas data step?

Suppose I allow a user to write their own variable calculation macro using a common user interface:

%macro calculate(var_name, var_value);
%* Some user-defined calculation;
%mend calculate;

Then in the data step, I can calculate the new variable using a custom 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 a dataset. Here I want to pass the variable name and the actual value of the variable. After calculation, put the value in new_var.

How can i achieve this?

+5
source share
4 answers

, , , . , SAS , , : , , SAS [1].

, :

%macro calculate (var_name, var_value);
  &var_name + &var_value;
%mend;

data one;
  input a@@;
  b = %calculate(a, 3);
  c = %calculate(a, a);
cards;
1 3 -2 4
;
run;

proc print data=one;
run;

macro %calculate , , SAS :

%macro calculate (var_name, var_value);
  &var_name + &var_value;
%mend;

data one;
  input a@@;
  b = a + 3;
  c = a + a;
cards;
1 3 -2 4
;
run;

proc print data=one;
run;

options mprint

, . , PROC FCMP /, DATA.

[1] , , .

+3

, ? , PROC FCMP , (fcmp = "function compiler" ), , .

:

proc fcmp outlib=sasuser.funcs.math;
  function calc(var);
     newvar=log(var); /*user defined stuff here - can be simple or complex*/
     return(newvar);
  endsub;
run;

option cmplib=sasuser.funcs; /*tell SAS where to look for functions*/
data _null_;
  set sashelp.class;
  newvar=calc(height); /*call your new function */
  put newvar=;
run;
+6

, , , .

, . SAS resolve(). , "% then" ( , ) , return() " ".

%macro compare(v1, v2);
  %if &v1 > &v2 %then v1 is greater than v2;
  %else v2 is greater than v1;
%mend;

data check (drop = macroCall);
  input v1 v2;
  macroCall = cats('%compare(', v1, ',', v2, ')');
  result = resolve(macrocall);
  datalines;
1 2
2 1
;

:

v1  v2  result
1   2   v2 is greater than v1
2   1   v1 is greater than v2
+2

This is a common point of confusion. The problem is that SAS processes all the macros in your program before any of the regular code. Therefore, when it calls %calculate('variable1', variable1);, it does not yet have access to the data in the data set.

However, it would be easier to help you come up with a solution if I had an example of what you could mean by %*Some user-defined calculation;.

0
source

All Articles