Hi,
Say I have a dataset with a couple of variables and I want to create a new variable being equal to sum of the two selected variables.
data have;
input year id sales_prod_A sales_prod_B sales_prod_C other_var;
datalines;
2010 1 100 80 100 500
2010 2 200 130 100 600
2010 3 300 50 200 500
2011 1 150 75 300 600
2011 2 275 150 400 200
2011 3 405 50 500 300
2012 1 190 200 600 400
2012 2 280 140 100 200
2012 3 420 70 200 600
;
run;
data want;
set have;
sales_prod_sum=sales_prod_A+sales_prod_B;
run;
Now, I want to do the same in the macro, so I try something like this.
%macro newvar (dataset, variable, suffix1, suffix2);
data want;
set &dataset;
&variable_sum=&variable_&suffix1 + &variable_&suffix2;
run;
%mend newvar;
%newvar (have, sales_prod, A, B);
Could you tell me what's wrong with the code?
To indicate the name of a macro variable has ended, you need to use a dot
%macro newvar (dataset, variable, suffix1, suffix2);
data want;
set &dataset;
&variable._sum=&variable._&suffix1 + &variable._&suffix2;
run;
%mend newvar;
If you don't use the dot, then the SAS macro processor thinks that &variable_ (with an underscore at the end) is the name of the macro variable, and no such macro variable exists.
To indicate the name of a macro variable has ended, you need to use a dot
%macro newvar (dataset, variable, suffix1, suffix2);
data want;
set &dataset;
&variable._sum=&variable._&suffix1 + &variable._&suffix2;
run;
%mend newvar;
If you don't use the dot, then the SAS macro processor thinks that &variable_ (with an underscore at the end) is the name of the macro variable, and no such macro variable exists.
If either of the variables might be missing and you still want the sum of what is actually present then use:
%macro newvar (dataset, variable, suffix1, suffix2);
data want;
set &dataset;
&variable._sum= sum(&variable._&suffix1,&variable._&suffix2);
run;
%mend newvar;
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.