'Open code statement recursion detected' when running %let %put statement (SAS Macro) - sas

When I run the following, it works fine:
%let mname = ABC<2>;
%put &mname;
ABC<2>
%let mname2 = %scan("&mname.", 2, '<>');
%put &mname2;
2
However, when I changed mname2 to the following, it gives the error:
%let mname2 = %scan("&mname.", 1, '<');
%put &mname2;
ERROR: Open code statement recursion detected.
Any idea what is causing it?

Since you added quotes around the value passed to the %SCAN() function and then only selected one of the quotes as the output you have generated unbalanced quotes.
In regular SAS code (and most programming languages) to allow the compiler to tell the difference between a variable name or a keyword and a string literal you add quotes around the string
But the macro processor language is different. To the macro processor everything is a string and it just looks for the & or % triggers to tell whether there is anything it needs to operate on.
49 %let mname = ABC<2>;
50 %put &=mname;
MNAME=ABC<2>
51 %put %scan(&mname,1,<>);
ABC
52 %put %scan(&mname,2,<>);
2
If you think it is possible the %SCAN() function will return unbalanced quotes or other things that might need macro quoting use the %QSCAN() function instead.

Related

assign macro variable output of tranwrd in macro function

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);

SAS accessing the macro variable name

I have some macro variables and each is assigned with a value. How can I get the name of the variables from their value?
For example I have assigned each person an age value. &Amy=12, &Peter=10.
I also have a macro function calculating something else, say weight.
%macro weight(name=);
%let weight=&name*10;
%put &name.'s weight is &weight.;
%mend;
if I run %weight(name=Amy) I want to get the result as "Amy's weight is 120".
how can i get the result as "Amy" instead of "12"?
Thanks
Nicely evil! That little single quote in the "Amy's" messes things up quite a bit. SAS seems to get confused about trying to evaluate the rest of the macro as a quoted string.
Start with the "magic string" to end all quotes, and make sure you've enabled macro output.
Once you do that, the following should work. Note the additional ampersands before name, as another responder suggested.
;*';*";*/;quit;
options mprint;
%let Amy = 12;
%macro weightmacro(name=);
%let weight=%sysevalf(&&&name..*10);
%put &name.s weight is &weight.;
%mend;
%weightmacro(name=Amy);
This will get you part of the way there. Note that having the apostrophe there is slightly problematic, you'll need to escape that or quote it out. I've ignored that for now. For the rest of your question:
Add more & to resolve a macro variable that's nested
Use %SYSEVALF() to do calculations with macro variables
%let Amy = 12;
%macro weight(name=);
%let weight=%sysevalf(&&&name*10);
%put &name. weight is &weight.;
%mend;
%weight(name=Amy);
If the point is the possessive noun that can be accomplished with %str(%');
357 %let Amy = 12;
358 %macro weightmacro(name=);
359 %let weight=%sysevalf(&&&name..*10);
360 %put &name.%str(%'s) weight is &weight.;
361 %mend;
362 %weightmacro(name=Amy);
Amy's weight is 120

%sysfunc CATS dropping characters

Consider the following text value '1/3/2016' from a dataset. This is a badly formatted date value that i cannot correct using ANYDTDTE. as I am on SAS 9.0. In this string the day and month are also the wrong way round. This is actually 03JAN2016 in date9. format
Therefore I have attempted to correct all of the above with the following macro:
%macro date_cats();
proc sql noprint;
select scan(matchdate,1,'/'), scan(matchdate,2,'/'), strip(scan(matchdate,3,'/')) into :month, :day, :year
from test;
quit;
%let padder = 0;
%if %length(&month) < 2 %then
%let month = %sysfunc(cats(&padder., &month.));
%put &month.;
%if %length(&day) < 2 %then
%let day = %sysfunc(cats(&padder., &day.));
%put &day.;
%put %sysfunc(cats(&day., &month., &year.));
%mend;
%date_cats();
The three %put statements produce the following in the log:
01
03
132016
Can anyone tell me in the final put statement why the final CATS statement is either dropping the added '0' character or reverting back to the macro variables being joined before they were padded out?
Thanks
Don't use CATS() to generate macro variables.
First it is totally unneeded since you can concatenate macro variable values by just expanding their values next to each other. Replace
%let month = %sysfunc(cats(&padder., &month.));
with
%let month = &padder.&month.;
Second when trying to evaluate the arguments to functions like CATS() that can take either numeric or character values %SYSFUNC() will attempt to evaluate your strings to see if they are numbers. In your case they are numbers so the leading zeros disappear. In other cases you can cause SAS to generate warning messages.
Third, if you really want to convert a string like 'M/D/Y' into a string like 'DMY' then assuming the string contains valid dates then just use formats to do the conversion.
%let have=1/20/2015 ;
%let want=%sysfunc(inputn(&have,mmddyy10),ddmmyyn8);
CATS is seeing numbers and automatically converting them, unhelpfully.
Generally for macro vars you can use the following
%put &day.&month.&year.;

Extraction of values from SAS Macro variable

I have defined macro variable
%let data_names = fuzzy_Data_segment EMWS2.Clus_TRAIN;
Then I have written a macro to extract and print the values from the above macro variable as:
%macro calling_data;
%do i = 1 %to 2;
%let data_name&i = %qscan(&data_names,&i);
%put &&data_name&i;
%end;
%mend;
%calling_data;
My macro code is able print the first name(fuzzy_Data_segment), but, it is only printing the part of the second name(EMWS2). what should I do to print the entire second name
Your issue is that SAS considers a period to be one of the default delimiters in macro variables. In this case, it looks like you want to be using a space to delimit items in data_names, so specify that:
%let data_name&i= %qscan(&data_names,&i., %str( ));
You're also missing semicolons in your %let statement and in your call to calling_data.

SAS macro quoting: pass equals sign as macro argument

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(&param));
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 ***&param***;
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 ***&param***;
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(&param); * 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(&param)); * 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(&param));
This can be circumvented by re-quoting the returned result using %str() again:
%put %left(%str(%trim(&param)));
... or wrapping the original parameter with a %nrstr():
%let param = %str( inobs = 2 );
%put %left(%trim(%nrstr(&param)));
... or using %sysfunc() to call a datastep function:
%put %sysfunc(compress(&param));