BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
chris2377
Quartz | Level 8

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?

1 ACCEPTED SOLUTION

Accepted Solutions
PaigeMiller
Diamond | Level 26

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.

--
Paige Miller

View solution in original post

2 REPLIES 2
PaigeMiller
Diamond | Level 26

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.

--
Paige Miller
ballardw
Super User

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;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 1139 views
  • 0 likes
  • 3 in conversation