SAS if statement in do loop - loops

Hi I am trying to write a macro function with do loop and if statement. I think I have messed up the if-then do and do loop and I can't figure out the problem.
I have a table of kids information, which contains columns like age, gender, sports, instruments etc,.
My original code, which works, looks like this:
data old;
set new;
if sports in ("football","basketball") and age <=7 then type =1;
else if sports='swimming' then type=2;
if special_kid=. then do;
if piano ^=. and piano_1 ^=. then do; talent_type=1; type_name=piano_1; end;
if violin ^=. and violin_1 ^=. then do; talent_type=1; type_name=violin_1; end;
end;
run;
I have a bunch of instruments that I want to edit the type and name. I want to write a loop to automatically do it, but I am not sure why the codes below doesn't work.
%let instrm = piano violin;
%macro my_func;
data old;
set new;
%if sports in ("football","basketball") and age <=7 %then type =1;
%else %if sports='swimming' %then type=2;
%do %while (special_kid=.);
%do i % to sysfunc(countw(&instrm));
%let word = %scan(&name, &i);
%if &word ^=. and ^word._1 ^=. %then %do;
talent_type=1; type_name=&word._1;
%end;
%end;
%end;
run;
%mend;
It keeps giving me the errors
ERROR: An unexpected semicolon occurred in the %DO statement.
ERROR: A dummy macro will be compiled.
Can anyone please answer my question? Thanks!

The macro variable instrm is really a value containing a space separated list of variable names. You might be better off abstracting away from the specific variable use role and fallback to a more generic parameter name vars. Also, rather than relying on a macro variable defined in a global or encompassing scope, pass the list in during invocation. You are correct that a space separated list can be iterated over in macro with a %do loop with a top limit that is the countw number of 'words' in the list--your syntax is only a little off.
You don't have to macro-ize everything, and the extra macroification of the sports logic went to far. Remember, macro invocations emit (or generates) source code that feeds into the SAS submit system. The macro coding coding process when more abstract or toolboxy is sometimes referred to as codegen.
Your original code may be faulty because you evaluate (in a single row) multiple special kid variables and perform value assignments to the same 2 variables (talent_type and type_name) and thus may overwrite a value previously assigned. Sometimes, such evaluations and assignments are OUTPUT to separate rows.
%macro my_skill_classifier(data=, out=, special_vars=, special_type=);
%local i var;
data &out;
set &data;
if sports in ("football","basketball") and age <=7 then type = 1;
else
if sports='swimming' then type=2;
* what happens to football/baskeball > 7yr ?;
if missing(special_kid) then do;
%do i = 1 %to sysfunc(countw(&special_vars));
%let var = %scan(&special_vars, &i);
* regular data step code with macro resolutions sprinkled in;
if &var ^=. and var._1 ^=. then do;
talent_type = &special_type;
type_name = &var._1;
* maybe you really mean type_name = "&var._1";
end;
%end; %* end loop over special_vars list;
end;
run;
%mend;
%my_skill_classifier(data=new, out=old, special_vars=piano violin, special_type=1)
In long, make sure your data shaping and evaluation processing methodology is rock solid before starting your macro coding. If you ask yourself Should I macro this?, be conservative and answer no. Be friendly to maintainers and future-self by not over complicating things.

There were few tweaks required in your code, I did some changes. Also, when we are using %if we always use macro variables. Otherwise we are good to use just if statements with normal dataset variables.
%let instrm = piano violin;
%macro my_func;
data old;
set new;
if sports in ("football","basketball") and age <=7 then type =1;
else if sports='swimming' then type=2;
if missing(special_kid) then do;
%do i=1 %to %sysfunc(countw(&instrm));
%let word = %scan(&instrm, &i);
%If &word ^=. and &word._1 ^=. %then %do;
talent_type=1; type_name=&word._1;
%end;
%end;
end;
run;
%mend my_func;

Related

Loop and join table

Let say I want to loop for i = 2002 to 2006 and in each loop, I create a key word like:
w2006
w2005
w2004
w2003
w2002
And each keyword will be the input for a macro, let say mymacro(keyword) which create a table named "result&key" (for example: resultw2006), so that I want to execute 5 time : %mymacro(w2006), %mymacro(w2005)... %mymacro(w2002) to have 5 tables and join them after that.
Do you have any idea of how to do this? In fact I tried but it doesn't work, here is my code:
%macro tojoin;
%do i=2002 %to 2006;
key=w&i;
%mymacro(&key);
%data result;
set result result&key;
%run;
output;
%end;
%mend;
You need to provide more information on what SAS code you are tying to use the macro processor to generate to get a real answer.
But assuming that %MYMACRO will generate a dataset named result&key then it looks like you want to run something like this to call it 5 times and append the results into a single dataset.
%macro tojoin;
%local key;
%do i=2002 %to 2006;
%let key=w&i;
%mymacro(&key);
proc append base=result data=result&key;
run;
%end;
%mend;
You don't need % in front of data or run, you need a %let statement, and you don't need the output command. So:
%macro tojoin;
%do i=2002 %to 2006;
%let key=w&i;
%mymacro(&key);
data result;
set result result&key;
run;
%end;
%mend;
Tom's method is cleaner, but your code was basically correct - just a bit of cleanup needed.

SYMBOLIC REFERENCE - SCAN function within DO LOOP

I am a relative novice to working with macro variables and seem to have gotten stuck.
I have a macro that opens a table and produces a macro variable &TBL_DIM. using PROC SQL select into.
%macro CREATE_DIM_VAR(tbl, var); %macro _; %mend _;
%syslput tbl = &tbl. / remote=gidwsas;
%syslput var = &var. / remote=gidwsas;
rsubmit;
PROC SQL NOPRINT;
*Create SELECT statement for columns we want;
SELECT ALL_DIM INTO: TBL_DIM SEPARATED BY ', '
FROM ALLDIM_LIST
WHERE TBL = "&TBL." AND VAR = "&VAR."
;
QUIT;
endrsubmit;
%mend;
%CREATE_DIM_VAR(A, GENDER);
When I do the following:
rsubmit;
%put &TBL_DIM.;
endrsubmit;
It works fine.
But now, when I try to call it within another macro:
%macro Execute(); %macro _; %mend _;
rsubmit;
%do n = 1 %to 10;
%let THIS_VAR = %scan(&TBL_DIM., &n.));
%put &THIS_VAR.;
%end;
endrsubmit;
%mend;
%Execute();
I get the error that:
WARNING: Apparent symbolic reference TBL_DIM not resolved.
How do I pass TBL_DIM over to the other macro?
EDIT:
When I modify %Execute() to run entirely from the Remote Server it works - but I still don't understand conceptually why...
rsubmit;
%macro Execute(); %macro _; %mend _;
%do n = 1 %to 10;
%let THIS_VAR = %scan(&TBL_DIM., &n.));
%put &THIS_VAR.;
%end;
%mend;
endrsubmit;
rsubmit;
%Execute();
endrsubmit;
I'm adding my last comment as an answer, as the reference below gives the definitive reason for the OP's observed behaviour.
Interaction between Compute Services and Macro Processing
http://support.sas.com/documentation/cdl/en/connref/61908/HTML/default/viewer.htm#a001584568.htm
In your non-working case, the local macro processor is processing the code within your rsubmit/endrsubmit block before sending the processed block to the remote server. However, when you declare a macro within the rsubmit/endrsubmit block, the entire macro is submitted and defined remotely.

How to use the && macro variable in SAS

I'm working with SAS and I have to create some macro variables within a DO loop. This is a portion of my code:
%if &dsempty888=0 %then %do;
data _null_;
set freq_&&var&i;
if &&var&i=888888888 then do;
call symput("cont8_&&var&i",percent);
end;
run;
%end;
%if &dsempty888=1 %then %do;
%let cont8_&&var&i=0;
%end;
%if &dsempty999=0 %then %do;
data _null_;
set freq_&&var&i;
if &&var&i=999999999 then do;
call symput("cont9_&&var&i",percent);
end;
run;
%end;
%if &dsempty999=1 %then %do;
%let cont9_&&var&i=0;
%end;
%if &dsempty444=0 %then %do;
data _null_;
set freq_&&var&i;
if &&var&i=444444444 then do;
call symput("cont4_&&var&i",percent);
end;
run;
%end;
%if &dsempty444=1 %then %do;
%let cont4_&&var&i=0;
%end;
This code is inside another DO loop that run from i=1 to &end.
With this my macro variables cont4_&&var&i cont8_&&var&i cont9_&&var&i are costantly overwrited...and they become unuseful outside of their loop. I tried to name them &&cont4_&&var&i for example. But clearly SAS doesn't solve the macro.
In practice inside of the loop the macro are created, but I don't know how to call them when I need outside.
How can I fix?
Thanks in advance.
You've got a lot of issues here, so let's simplify this some. Here's a very simplified example. This, for example, does something:
%let var1 = age;
%let var2 = height;
%let var3 = weight;
proc freq data=sashelp.class noprint;
tables age/out=freq_age;
tables height/out=freq_height;
tables weight/out=freq_weight;
run;
%macro get_freqs(var_count=);
%do i = 1 %to &var_count.;
data _null_;
set freq_&&var&i;
call symput("cont4_&&var&i",percent);
run;
%end;
%mend get_freqs;
%get_Freqs(var_count=3)
But now if we do
%put cont4_&&var&i;
Of course it doesn't work, since &i has no meaning. So instead we replace that with, say, 1:
%put cont4_&&var1;
Now we get something. But we don't get anything useful, do we, just the variable name. But - at least that's something!
Now we don't really need the second & there, right?
%put cont4_&var1;
But we need a & before this to use the macro variable:
%put &cont4_&var1;
But now we get a warning message, CONT4_ not resolved. Okay, let's add a second & to delay the resolution of the macro variable until &var1 is resolved.
%put &cont4_&var1;
Well, that helped, now it says CONT4_AGE not resolved. Why not? We used call symput to define that, right?
The problem is scoping. call symput probably scoped it locally, meaning it was defined in the macro but not outside of the macro. For this we use call symputx and give it a global scope.
%macro get_freqs(var_count=);
%do i = 1 %to &var_count.;
data _null_;
set freq_&&var&i;
call symputx("cont4_&&var&i",percent,'g');
run;
%end;
%mend get_freqs;
This tells SAS that I want &cont4_age to be defined outside of the macro. Otherwise it will only be available locally - inside the macro - and will get cleaned up.
Now, this works:
%put &&cont4_&var1;
But if you wanted to iterate over &i again, it's a bit more complex. That's because you need to delay those ampersands multiple times, and allow several passes.
Here's what works:
%macro iterate_i(var_count=);
%do i = 1 %to &var_count.;
%put &&&&cont4_&&var&i.;
%end;
%mend iterate_i;
%iterate_i(var_count=3);
Why do we need four &s? Well, we need to get to &&cont4_&var1, right? That happens in the first pass. Here are the three passes:
&&&&cont4_&&var&i -> &&cont4_&var1 -> &cont4_age -> 5.26...
Each pass, the following happens:
&& -> & (and save for next pass)
& -> resolve macro variable
So, that's how you'd iterate over those. You can of course explicitly specify at any level the macro variable - so all of these work:
%let i=1;
%put &&&&cont4_&&var&i;
%put &&cont4_&var1;
%put &cont4_age;

Logic to leave loop not working SAS

I want to repeat some code, varying one of the parameters and test whether a condition is met. If the condition is met, I want to leave the loop, if not I want to proceed to the next value of the parameter. I am using the below code, which works fine except that it does not leave the loop when I expect it to. Despite the summary showing that the condition should have been met it always seems to resolve to False.
%macro set_downward_caps(year, in_year_tolerance, large, small, start, end, increment);
%do c = &start. %to &end. %by &increment.;
%let nominal_down_large_&year. = %sysevalf(&large. + (&c. / 1000));
%let nominal_down_small_&year. = %sysevalf(&small. + (&c. / 100));
%let real_down_large_&year. = %sysevalf((1 - &&nominal_down_large_&year.) * &&rpi&year.);
%let real_down_small_&year. = %sysevalf((1 - &&nominal_down_small_&year.) * &&rpi&year.);
%rates(&year.);
proc means data = output.s_&scenario. noprint nway;
var transbill&year.;
output out = temporary (drop = _type_ _freq_) sum=cost;
run;
data _null_;
set temporary;
call symput('cost', cost);
run;
data temp;
length scenario $ 30;
scenario = "&scenario.";
large = &&real_down_large_&year.;
small = &&real_down_small_&year.;
cost = &cost.;
run;
data output.summary_of_caps;
set output.summary_of_caps temp;
run;
%if %sysfunc(abs(&cost.)) le &in_year_tolerance. %then leave;
%end;
%mend set_downward_caps;
So the sumary_of_caps table contains values that suggest that the following condition should have resolved to true:
%if %sysfunc(abs(&cost.)) le &in_year_tolerance. %then leave;
I've tried sticking it in sysevalf but to no avail.
I don't think there is a LEAVE equivalent for macro code. Why not just use a %GOTO? Or since you seem to want to totally leave the macro you could use %RETURN.
Also if you are comparing floating point numbers you need to use %SYSEVALF(). The implied %EVAL() call of the %IF statement will only handle integer arithmetic.
%if %sysevalf(%sysfunc(abs(&cost)) le &in_year_tolerance) %then %return;
Why do the calculations in macro logic at all? I am not sure why you have all of those macro variables, unless the %RATES() macro is referencing them? But if it needs them why aren't they parameters to the macro like you are passing in &YEAR?
You have plenty of data steps in your current code where you could do the calculation there and just set a flag variable that you can use to control whether to exit the loop.
%macro set_downward_caps
(year
,in_year_tolerance
,large
,small
,start
,end
,increment
);
%local c leave ;
%do c = &start %to &end %by &increment;
%local nominal_down_large_&year ;
%local nominal_down_small_&year ;
%local real_down_large_&year ;
%local real_down_small_&year ;
%let nominal_down_large_&year. = %sysevalf(&large. + (&c. / 1000));
%let nominal_down_small_&year. = %sysevalf(&small. + (&c. / 100));
%let real_down_large_&year. = %sysevalf((1 - &&nominal_down_large_&year.) * &&rpi&year.);
%let real_down_small_&year. = %sysevalf((1 - &&nominal_down_small_&year.) * &&rpi&year.);
%rates(&year.);
proc means data = output.s_&scenario. noprint nway;
var transbill&year.;
output out = temporary sum=cost;
run;
data temp;
length scenario $ 30;
scenario = "&scenario.";
large = &&real_down_large_&year.;
small = &&real_down_small_&year.;
set temporary (keep=cost);
call symputx('leave',abs(cost) le &in_year_tolerance);
put (_all_) (=);
run;
data output.summary_of_caps;
set output.summary_of_caps temp;
run;
%if (&leave) %then %goto quit;
%end;
%quit:
%mend set_downward_caps;

how to excute sas macro iteratively in another macro?

i would like to get result of brand_channel macro.
macro is not working on i=2,3,4 in %do-loop statement.
How can I execute doing_scoring macro iteratively?
thanks!
%doing_scoring;
...
...
...
%mend doing_scoring;
%macro brand_channel;
proc sql noprint;
create table oneb_onec as
select unique x1, x2
from mydata_all;
quit;
data seq_oneb_onec;
set oneb_onec;
seqno = _N_;
run;
%let num=4;
%do i=1 %to &num;
%put doing number is &i;
%put end doing number is &num;
proc sql noprint;
create table onebc_table&i as
select a.*
from mydata_all a, seq_oneb_onec b
where b.seqno = &i
and b.x1 = a.x1
and b.x2 = a.x2;
quit;
%doing_scoring(mydata=onebc_table&i, setnumber = &i);
%end;
%mend brand_channel;
%brand_channel;
Your code is fine, except for the initial line (declaration of doing_scoring), but that's likely transcription error I suppose.
Below I have a functional test version.
However, I have a better way to do the same thing. Fundamentally, macro driven iteration is a bad idea; there is a better way to do almost every task you might want to attempt.
In this case, you can call the doing_scoring calls directly from the seq_ dataset, and either move the creation of the sub-dataset to the macro (should be easy) or, perhaps better, keep the dataset in one piece.
First the better way: call execute. (Or, you can create the macro calls in SQL using select into.)
proc sort data=sashelp.class out=class;
by age sex;
run;
%macro doing_scoring(data=,age=,sex=,setnumber=);
data mydata;
set class;
where age=&age. and sex="&sex.";
run;
*whatever else you are doing;
%mend doing_scoring;
data _null_;
set class;
by age sex;
if first.sex then seqno+1;
callstr=cats('%doing_scoring(data=class,age=',age,',sex=',sex,',setnumber=',seqno,')');
call execute(callstr);
run;
Now, the original way with same test data.
%macro doing_scoring(mydata=,setnumber=);
%put doing_scoring &mydata. &setnumber.;
%mend doing_scoring;
%macro brand_channel;
proc sql noprint;
create table oneb_onec as
select distinct age,sex
from sashelp.class;
quit;
data seq_oneb_onec;
set oneb_onec;
seqno = _N_;
run;
%let num=4;
%do i=1 %to &num;
%put -------------------;
%put doing number is &i;
%put end doing number is &num;
proc sql noprint;
create table onebc_table&i as
select a.*
from sashelp.class a, seq_oneb_onec b
where b.seqno = &i
and b.age = a.age
and b.sex = a.sex;
quit;
%doing_scoring(mydata=onebc_table&i, setnumber = &i);
%put -------------------;
%end;
%mend brand_channel;
%brand_channel;

Resources