DATA Step, Macro, Functions and more

Updating global macro variable based on a condition

Accepted Solution Solved
Reply
Contributor
Posts: 25
Accepted Solution

Updating global macro variable based on a condition

I have a global variable called "switch", which by default is set to 'N'; If a certain condition occurs then I'd like switch be = 'Y'. The code I'm using always changes switch to 'Y', regardless of the condition. That's not right. Here's my code: data _NULL_; %let switch = N; if rand('UNIFORM') > 0.3 then do; %let switch = 'Y'; end; %put &switch; run; Any ideas? Thanks!
Andrew A. Kramer, PhD
President
Prescient Healthcare Consulting

Accepted Solutions
Solution
‎06-29-2017 03:52 PM
Super User
Posts: 5,071

Re: Updating global macro variable based on a condition

%LET statements are never part of a DATA step.  You might as well have coded:

 

%let switch = N;

%let switch = 'Y';

%put &switch;

data _NULL_;

if rand('UNIFORM') > 0.3 then do;

end;

run;

 

That reflects what your program is actually doing.  However, the good news is that there are interfaces between a DATA step and macro language.  You could instead code:

 

%let switch = N;

data _null_;

if rand('UNIFORM') > 0.3 then call symput('switch', 'Y');

run;

%put &switch;

 

View solution in original post


All Replies
PROC Star
Posts: 7,356

Re: Updating global macro variable based on a condition

Two problems: 1 you change it from N to 'Y' (why do you add quotes for Y?)

2 You use %let let in a datastep, when you should use call symput

 

What condition do you really want to use? Surely, not just randomly like shown in your code.

 

Art, CEO, AnalystFinder.com

Contributor
Posts: 25

Re: Updating global macro variable based on a condition

The quotes around Y are a mistake. I wasn't aware (but now am!) that I can't use %let in the data step. So how would I use call symput to do what I intended? Thanks!
Andrew A. Kramer, PhD
President
Prescient Healthcare Consulting
Solution
‎06-29-2017 03:52 PM
Super User
Posts: 5,071

Re: Updating global macro variable based on a condition

%LET statements are never part of a DATA step.  You might as well have coded:

 

%let switch = N;

%let switch = 'Y';

%put &switch;

data _NULL_;

if rand('UNIFORM') > 0.3 then do;

end;

run;

 

That reflects what your program is actually doing.  However, the good news is that there are interfaces between a DATA step and macro language.  You could instead code:

 

%let switch = N;

data _null_;

if rand('UNIFORM') > 0.3 then call symput('switch', 'Y');

run;

%put &switch;

 

Contributor
Posts: 25

Re: Updating global macro variable based on a condition

That works! Thanks.
Andrew A. Kramer, PhD
President
Prescient Healthcare Consulting
☑ This topic is SOLVED.

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

Discussion stats
  • 4 replies
  • 108 views
  • 0 likes
  • 3 in conversation