DATA Step, Macro, Functions and more

Macro variable in the loop;

Accepted Solution Solved
Reply
Contributor
Posts: 49
Accepted Solution

Macro variable in the loop;

Hi,
I have unexpected result from the call symput function of SAS.

I wrote this code:

data tab1;
	a=1; b=2; output;
	a=3; b=5; output;
run;

%macro loop;
	data tab2;
		set tab1;
		%do i=1 %to 2;
			call symput(cats('var',&i),a);
			call symput(cats('dem',&i),b);
		%end;
	run;

	%do i=1 %to 2;
		%put i &&var&i &&dem&i;
	%end;
%mend;

%loop;

from this code I get the result:

 

1 3 5
2 3 5

Instead of :

1 1 2

2 3 5

 

(In linux...sas doesn't recognize the macro variable &&var&i ).

 

I can't understand why... I need to save some variable in the macro variable... some of you has some solution and explain why I get this result? really..I can't understand..

Thanks

 

 

 


Accepted Solutions
Solution
‎07-21-2017 04:11 PM
Super User
Posts: 5,503

Re: Macro variable in the loop;

There's always a way.  Here's one idea:

 

data tab2;

set tab1;

call symput(cats('var',_n_), a);

call symput(cats('dem',_n_),b);

run;

View solution in original post


All Replies
Super User
Posts: 5,503

Re: Macro variable in the loop;

The statements execute in a different order than you are expecting.  Your code adds four statements to the DATA step, creating:

 

data tab2;

set tab1;

call symput(cats('var',1), a);

call symput(cats('dem',1),b);

call symput(cats('var',2),a);

call symput(cats('dem',2),b);

run;

 

All of that occurs before the DATA step begins to run.  Once all the statements are complete, the DATA step executes.  So for the first observation from TAB1, all four statements execute.  Then for the second observation from TAB1, all four statements execute, replacing the values assigned previously.

 

Contributor
Posts: 49

Re: Macro variable in the loop;

[ Edited ]
Posted in reply to Astounding

Thanks Astounding,
Your answer is very clear!!!

 


but.. if i want to save some variable of data set in the macro, what should i do? 

because i haven't any idea...

 

Thanks.

Solution
‎07-21-2017 04:11 PM
Super User
Posts: 5,503

Re: Macro variable in the loop;

There's always a way.  Here's one idea:

 

data tab2;

set tab1;

call symput(cats('var',_n_), a);

call symput(cats('dem',_n_),b);

run;

Contributor
Posts: 49

Re: Macro variable in the loop;

Posted in reply to Astounding

Wow!!

Thanks Astounding!!!

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 123 views
  • 1 like
  • 2 in conversation