I am trying to do a macro that takes other macros as an input, and these macros can have a different number of parameters. So imagine I have a macro:
%MACRO foo(text = );
%PUT &text.;
%MEND foo;
And I want to create a call_macro macro that calls foo(), specifying the text. The issue is that I might want to call another macro fuu() with other parameters.
I've thought of something like that:
%MACRO call_macro(macro = , args = );
%¯o.(&args.);
%MEND call_macro;
%call_macro(macro=foo, args='text=Hello');
Which obviouslly does not work, because I am calling %foo('text=Hello') instead of %foo(text=Hello). Is there a way out of this?
(For context, I am trying to create a map function, used in R, for SAS. The objective would be to have a function map that takes a list of datasets, a function to be applied, and the parameters of that function, performs that function on all datasets)
If you want to work with DATA in SAS then use SAS data steps and procedures. This is true even if the data is actually metadata about code you want to run.
So if you have a dataset with three variables, REMOTE, MACRO and ARGS you can use that to generate a series of RSUBMIT/ENDRSUBMIT blocks to send the macro calls to each of the different parallel processes. Then just use %INCLUDE to run the generated code.
filename code temp;
data _null_;
set metadata ;
by remote ;
file code;
if first.remote then put 'rsubmit ' remote ';' ;
put '%' macro '(' args ');';
if last.remote then put 'endrsubmit;' ;
run;
%include code / source2;
In reality the RSUBMIT statement might need to be more complex to really implement parallel execution, but the idea of how to generate the code from the metadata is the point.
Just omit the quotes.
%MACRO call_macro(macro = , args = );
%¯o.(&args.);
%MEND call_macro;
%call_macro(macro=foo, args=text=Hello);
it would not work if you would have called your macro without equality signs
because in your call
%call_macro(foo, text=Hello);
the second argument would not be interpreted as having a value text=Hello, but as a parameter text with value Hello.
If you code your dispatching macro with the PARMBUFF option, you do not need to embed your arguments within another parameter. PARMBUFF supplies the macro the parameters, including any bounding parentheses.
Example:
Supply the dispatched macros arguments as first-order arguments to the dispatching macro.
%macro one (data=);
%put INFO: Macro:&SYSMACRONAME. &=data;
%mend;
%macro two (data=, vars=);
%put INFO: Macro:&SYSMACRONAME. &=data &=vars;
%mend;
%macro three (data=, vars=, out=);
%put INFO: Macro:&SYSMACRONAME. &=data &=vars &=out;
%mend;
%macro dispatch (macro=) / PARMBUFF;
%put INFO: -----;
%put INFO: &SYSMACRONAME. &=SYSPBUFF;
%put INFO: &=macro;
%if %length(¯o) %then %do;
%let syspbuff = %sysfunc(prxchange(%str(s/,?\s*macro\s*=\s*\w+,?//i),-1,&syspbuff));
%local invoke;
%let invoke = ¯o &syspbuff;
%&invoke
%end;
%put INFO: -----;
%mend;
%dispatch(macro=one, data=foobar)
%dispatch(data=foobar, macro = one)
%dispatch(macro=two, data=foobar, vars=p q r)
%dispatch(macro=three, data=foobar, vars=p q r, out=snafu)
%one (data=x)
will log
INFO: -----
INFO: DISPATCH SYSPBUFF=(macro=one, data=foobar)
INFO: MACRO=one
INFO: Macro:ONE DATA=foobar
INFO:
INFO: -----
INFO: DISPATCH SYSPBUFF=(data=foobar, macro = one)
INFO: MACRO=one
INFO: Macro:ONE DATA=foobar
INFO:
INFO: -----
INFO: DISPATCH SYSPBUFF=(macro=two, data=foobar, vars=p q r)
INFO: MACRO=two
INFO: Macro:TWO DATA=foobar VARS=p q r
INFO:
INFO: -----
INFO: DISPATCH SYSPBUFF=(macro=three, data=foobar, vars=p q r, out=snafu)
INFO: MACRO=three
INFO: Macro:THREE DATA=foobar VARS=p q r OUT=snafu
INFO:
INFO: Macro:ONE DATA=x
If you did want to do this then you need to protect the commas in the arguments to the submacro. You could try macro quoting or actual quoting. But it would be simplest to take advantage of the fact that commas inside of parentheses in a macro call do not get treated as indicating start of a new parameter.
So just pass the macro call without the % as the single argument to the CALL_MACRO macro.
%macro call_macro(arg);
%put &=sysmacroname: &=arg ;
%&arg.
%mend;
%macro test1(a,b=);
%put &=sysmacroname: &=a &=b ;
%mend;
%macro test2(c,d,e);
%put &=sysmacroname: &=c &=d &=e;
%mend;
%call_macro(test1(b=xyz,a=123))
%call_macro(test2(456,e=abc,d=89))
%call_macro(foo(text=Hello))
If for some reason CALL_MACRO needed to know the name of the macro it is going to call that could be extracted with a simple %SCAN() function call.
%local macroname;
%let macroname=%scan(&arg,1,());
I worked it out. Set args="par_1=val_1, par_2=val_2" and then inside the macro, use args=%sysfunc(COMPRESS(&args.,'"');
Related
I need to store a value from a table into a variable. I've tried let, symputx, and select into. In the current version I try to use symputx, but the variable is not being updated. The products table contains type, price_floor, price_tier1, price_tier2.
%global price1;
%global price2;
%macro container();
DATA _null_;
SET products;
IF type = "Single" THEN DO;
CALL SYMPUTX('price1', price_floor,'g');
END;
IF type = "Multi" THEN DO;
CALL SYMPUTX('price1', price_tier1,'g');
CALL SYMPUTX('price2', price_tier2,'g');
END;
%PUT &=price1;
%PUT &=price2;
%mend;
Both price1 and price2 are null.
SYMBOLGEN: MACRO variable PRICE1 resolves to PRICE1=
SYMBOLGEN: MACRO variable PRICE2 resolves to PRICE2=
You don't have a run statement on your datastep, so your %put statement is being written to the log before the data step executes - so, the variables don't exist yet. It won't be run until you do provide a run statement or step boundary, or SAS might do that politely for you when the program is finished, but either way it's not being run before the %put.
Usually, this kind of program is an anti-pattern in SAS; you don't provide sufficient context, so maybe it's okay, but this will only work if you have only one row in the dataset - otherwise it probably won't do anything useful. The key word that's triggering me to write this is that you called this a "variable" - not a "macro variable" - in your question; SAS macro variables are not really "variables" and not meant to be used like a C variable or Python variable.
FYI to anyone interest, I decided to restructure the program as a whole. The original plan was to pass elements of a user defined array into %container, then use the assigned macro variables price1 and price2 as parameter in another macro call.
Instead of imbedding this data step in a macro, I created a table to contain all of the inputs I planned to pass into %container. Then I just used executes with the table variables concatenated within instead of direct macro calls.
data _null_;
SET products;
IF type = "Single" THEN DO;
CALL execute('%split_prod('||price_floor||');');
END;
IF type = "Multi" THEN DO;
CALL execute('%select_prod('||price1||','||price2||');');
END;
run;
There isn't anything wrong with the code besides the RUN.
%global price1;
%global price2;
data products;
infile cards dlm=',';
input Type $ price_floor price_tier1 price_tier2;
cards;
Multi, 40, 20, 60
;;;;;
%macro container();
DATA _null_;
SET products;
IF type = "Single" THEN DO;
CALL SYMPUTX('price1', price_floor,'g');
END;
IF type = "Multi" THEN DO;
CALL SYMPUTX('price1', price_tier1,'g');
CALL SYMPUTX('price2', price_tier2,'g');
END;
RUN;
%mend;
%container();
%PUT &=price1;
%PUT &=price2;
LOG:
96 %PUT &=price1;
PRICE1=20
97 %PUT &=price2;
PRICE2=60
You never showed your call for %container() so not sure what the underlying issue is, but CALL EXECUTE is a better method as debugging macros is painful.
I can't figure out this seemingly trivial problem - expect macro variable to be assigned mpg_city.
%macro test(col=);
%let id = %sysfunc(tranwrd(&col, 'extra_', ''));
%put &id;
%mend test;
%test(col=extra_mpg_city);
Current output is extra_mpg_city.
Arguments listed in a function invoked through %sysfunc are implicitly text and should not be quoted. Placing quotes in a sysfunc invoked function is like nesting quotes in a DATA step invocation.
Try
%let id = %sysfunc(tranwrd(&col, extra_, %str()));
The DATA Step analog is
id = tranwrd("&col", "extra_", "");
Your original code in DATA Step analog (below) should show why the tranwrd did not operate as you expected.
id = tranwrd("&col", "'extra_'", "''");
You don't need the quotes when using string functions with %sysfunc, unless you expect to find them in the input. Try this:
%macro test(col=);
%let id = %sysfunc(tranwrd(&col, extra_, ));
%put &id;
%mend test;
%test(col=extra_mpg_city);
I'm using SYSPBUFF to pass through various numbers of parameters into a macro. Specifically, I am passing through a list of states. One of the states being used is Oregon or "OR" and that one state is causing me error.
I get the error "ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric operand is required. The condition was: &ST^=
ERROR: The condition in the %DO %WHILE loop, &ST^=, yielded an invalid or missing value, . The macro will stop executing.
I've used all the various quoting masks to try to resolve this issue but none of it is working.
&STATES includes the following states:
AK,AZ,CA,HI,ID,NV,OR,WA
Here is my current code:
RSUBMIT;
PROC SQL;
connect to oracle
(path=DW user=&USER pw=&PW);
%macro DTCNT() / parmbuff;
%let i=1;
%let ST=%scan(&SYSPBUFF,&I);
%do %while (&ST^=);
CREATE TABLE MD_&ST._IP_ADJDT_CNTS_S1 AS
select *
from connection to oracle
(SELECT adjudication_date,
count (*) as LINE_CNT
from MD_r&NUM..&ST._IP_hdr_f
group by adjudication_date
order by adjudication_date);
%let i=%eval(&I+1);
%let ST=%scan(&SYSPBUFF,&I);
%end;
%mend DTCNT;
%DTCNT(&STATES);
disconnect from oracle;
QUIT;
ENDRSUBMIT;
Any assistance would be greatly appreciated.
Thanks in advance.
The issue here is Oregon. Its abbreviation is OR, which is also a reserved word (oops!). Remember the macro language is just text that is then parsed like normal - so when it finds &ST and translates to OR, it sees that as
%do %while (or ^= )
which causes it to get confused since it doesn't see anything to use with or.
You can use macro quoting here to cause SAS not to treat it like the boolean operator. %SUPERQ is the goto one for me, but a few of them should work.
Here's an example. I added some extra stuff to scan also to handle the parens.
%let states=AK,AZ,CA,HI,ID,NV,OR,WA;
%macro DTCNT() / parmbuff;
%let i=1;
%put &=syspbuff.;
%let ST=%scan(&SYSPBUFF,&I,%str(%(%),));
%put &=st.;
%do %while (%superq(ST)^=);
%put &=st;
%let i=%eval(&i.+1);
%let ST=%scan(&SYSPBUFF,&I,%str(%(%),));
%end;
%mend DTCNT;
%DTCNT(&STATES);
There is a great paper on how to test for empty macro variables, Chang Chung's Is This Macro Parameter Blank.
For your simple program I find it much easier to just use %length() to test for empty macro variables.
%do %while (%length(&ST));
I'm looking to create a loop such that I run two macros for each dataset
%Let Classification = Data1 data2 data3 data4;
%let index = 1;
%do %until (%Scan(&Classification,&index," ")=);
%Macro1;
%Macro2;
%end;
%let index = %eval(&Index + 1);
The problem is my macros are not pre-loaded and are stored in a macro library, is it possible to do this if I run the above as a macro?
Any advice is appreciate in making this loop of macros work
EDIT:
In my ideal situation the loop would run like a macro
%Macro;
where inside it would look like
%Macro Macro;
%let index = 1;
%do %until (%scan(&classification,&index," ")=);
<Lines of Code>
%end;
%let index = %eval(&Index + 1);
%end;
%mend;
Another problem is my macros enclosed in the loop use the &classification to differentiate between data1, data2, data3, data4 as we process through the different lines of code.
It is probably easier to just iterate over the index. Use the countw() function to find how many iterations to do.
%macro loop(list);
%local index next ;
%do index=1 %to %sysfunc(countw(&list,%str( )));
%let next=%scan(&list,&index,%str( ));
... code to process &NEXT ...
%end;
%mend ;
Then pass in the list to the macro as the parameter value.
%Let Classification = Data1 data2 data3 data4;
%loop(&classification);
SAS does not allow the %DO statement in open-code. When you submit an open code loop you will get log messages
ERROR: The %DO statement is not valid in open code.
...
ERROR: The %END statement is not valid in open code.
as #Tom mentioned the macro %SCAN test should check for null string. Another common and more robust way is to check before token extraction. %do %until will iterate poorly when the classification passed is empty. A %do %while tests the classification scan prior to interior macro invocations. Another common test for null macro value is checking for 0 length and leveraging 0=false ^0=true automatic evaluation.
When the loop is to call other macros with the token value the best practice is to pass the token value instead of having the called macro presume the token symbol (aka macro variable) already exists (in a containing scope) prior the iterated macros invocation.
Example
%macro mydispatch (classification=);
%local index token;
%let index = 1;
%do %while ( %length (%scan (&classification, &index)));
%let token = %scan(&classification,&index));
%* emit code specifically for token;
* this is for &token;
%* iterated invocations, perform two analysis for each data set listed in classification;
%* second analysis is passed another argument specifying the data set that should be used to store output;
%analysis_1 (data=&token)
%analysis_2 (data=&token, out=WORK.results_&token.)
%let index = %eval(&index+1);
%end;
%mend mydispatch;
%mydispatch (classification=data1 data2 data3 data4)
The macro being in an autocall library (which is what I assume you refer to?) does not have any impact on how the above would work. If it's not in an autocall library you'll have to hook up the catalog up to the autocall library first.
In re: your edits; yes, you will need this to be in a macro (I assumed it was a subset of a macro initially). %do is not currently allowed in open code (this may change, but not today).
Note you have several significant issues in your code:
the incrementor is not in the loop
the scan function is wrong; macro language does not use quotations, so
%do %until (%Scan(&Classification,&index," ")=);
needs to be
%do %until (%Scan(&Classification,&index)=);
(space is the default separator), and if you really needed to clarify space:
%do %until (%Scan(&Classification,&index,%str( ))=);
Your macros do not utilize parameters; they should. %macro1; apparently uses &classification and &index; instead you should pass it the thing you want (the "word" from &classification) as a parameter.
I am writing a macro that at some point calls some proc SQL code. I want the user to be able to specify arbitrary proc sql options (e.g. inobs=100 could be one of the input arguments to my macro).
I am having a very hard time quoting an argument that has an equality '=' character.
One of the issues is that I should also check if the macro argument is empty or not, and if it is not empty, only then add the specified options to the sql statement.
Below is an example non-working test that does not work and throws the
ERROR: The keyword parameter INOBS was not defined with the macro.
I have read this (http://www2.sas.com/proceedings/sugi28/011-28.pdf) and other SUGI's and tried many possible ways to quote and call the macro.
If somebody could provide a working example of the below function it would be greatly appreciated.
options mprint mlogic;
data have;
length x $8;
input x;
datalines;
one
two
three
;
proc sql inobs=2;
create table sql_output as
select *
from have;
quit;
%macro pass_parameter_with_equal_sign(table=, sqlOptions=);
proc sql
%if "%left(%trim(&sqlOptions.))" ne "" %then %do;
&sqlOptions.
%end;
/* the semicolon to end the proc sql statement */
;
create table macro_output as
select *
from have;
quit;
%mend;
%pass_parameter_with_equal_sign(table=have, sqlOptions=%str(inobs=2))
title "SQL output:";
proc print data=sql_output; run;
title "Macro output:";
proc print data=macro_output; run;
If you remove the %if condition as follows it should work:
%macro pass_parameter_with_equal_sign(table=, sqlOptions=);
proc sql
&sqlOptions.
/* the semicolon to end the proc sql statement */
;
create table macro_output as
select *
from have;
quit;
%mend;
The %if you have used is to check if &sqlOptions is not blank, this shouldn't matter if you use it as it is because its unconditional usage will give either:
proc sql inobs=2; /* in the case of &sqlOptions=inobs=2 */
or if there is no value supplied for &sqlOptions then you should see:
proc sql; /* i.e. no options specified */
So it should work with or without an argument.
Amir's solution is probably correct for your particular use case. But to answer the more general question, we need to look to the seminal paper on macro parameter testing, Chang Chung's Is This Macro Parameter Blank?.
His example C8 is the right one for you here, though some of the others will also work.
%if %sysevalf(%superq(param)=,boolean) %then ... /* C8 */
For example:
%macro test_me(param=);
%if %sysevalf(%superq(param)=,boolean) %then %put Empty;
%else %put Not Empty;;
%mend test_me;
%test_me(param=);
%test_me(param=MyParam);
%test_me(param=param=5);
%SUPERQ is most useful here because it avoids resolving the macro parameter. Instead, it keeps it as a macro parameter value - fully unresolved - and allows you to work with it in that fashion; so you have no risk of that pesky equal sign bothering you.
His C4 (just using SUPERQ without SYSEVALF) also works in this case, although he explains a few situations where it may have difficulty.
Ahh this was actually a tricky little problem you ran into. The issue was actually being caused by the calls to %trim() and %left().
Removing these results in code that works as intended (note I also removed the macro quoting around the parameter):
%macro pass_parameter_with_equal_sign(table=, sqlOptions=);
proc sql
%if "&sqlOptions" ne "" %then %do;
&sqlOptions
%end;
/* the semicolon to end the proc sql statement */
;
create table macro_output as
select *
from &table;
quit;
%mend;
%pass_parameter_with_equal_sign(table=sashelp.class, sqlOptions= inobs=2);
We can re-create the issue you were experiencing like so:
%put %trim(inobs=1);
Because the parameter was resolving to inobs=1, and %trim() doesn't have any named parameters, it was throwing a hissy fit. To correctly pass in a string that contains "inobs=1" we can do so like this:
%let param = inobs=1;
%put %trim(%str(¶m));
Note: Amir's solution of removing the %if statement altogether is also the best way to design code like this. I'm just providing more details as to why you were having this issue.
Additional Explanation 1 - Why %left() and %trim are not needed
The top code snippet provides the same intended functionality as your original code that had the "%left(%trim(&sqlOptions.))". This is because beginning and ending whitespace is dropped from macro variables (including macro parameters) unless it is explicitly retained by using macro quoting. A simple example to show this is:
%let param = lots of spaces ;
%put ***¶m***;
Gives:
***lots of spaces***
You can see that the internal whitespace is kept, but the left and right padding are gone. To keep whitespace, we can simply use the %str() function.
%let param = %str( lots of spaces );
%put ***¶m***;
Gives:
*** lots of spaces ***
Additional Explanation 2 - Working with macros containing whitespace
If you actually did have whitespace on a macro variable that you needed to remove because it was quoted, and you wanted to use %left() and %trim() to do so, then things get a little wacky. Our variable can be created like so:
%let param = %str( inobs = 2 );
You can see we already have quoted the value with %str() in order to create it. This means we can now call one of the functions without having to quote it again:
%put %trim(¶m); * ALREADY QUOTED AT CREATION SO THIS WORKS FINE;
However, if we then try and feed the result into the %left() function we're back to the original issue:
%put %left(%trim(¶m)); * OOPS. DOESNT WORK;
Now I'm guessing here but I believe this is most likely because the %trim() function removes any macro quoting prior to returning a result. Kind of like this:
%put %unquote(%trim(¶m));
This can be circumvented by re-quoting the returned result using %str() again:
%put %left(%str(%trim(¶m)));
... or wrapping the original parameter with a %nrstr():
%let param = %str( inobs = 2 );
%put %left(%trim(%nrstr(¶m)));
... or using %sysfunc() to call a datastep function:
%put %sysfunc(compress(¶m));