SAS accessing the macro variable name - sas

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

Related

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

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.

How to remove suffixes from a set of addresses

I have a data set containing a list of street addresses. Some of these addresses end in a suffix like "AVE" or "ROAD". I want to remove any of these suffixes that appear in the list of addresses. My approach is to use a Do loop to step through a list.
%macro suffixes(field=,newfield=);
%let suffix = AV AVE AVENUE BEACH BLUFF BLVD BOULEVARD;
%let nwords=%sysfunc(countw(&suffix));
%do i=1 %to &nwords;
%let suff=%scan(&suffix,&i);
%let sufflen=%length(&suff);
%if %substr(&field,%length(&field)-&sufflen)=&suff
%then &newfield=%substr(&field,1,%length(&field)-&sufflen+1);
%end;
%mend;
data addresses_no_suffix;
set addresses_full;
%suffixes(field=addresses,newfield=new_addr);
run;
I'm kind of stuck, as the above approach doesn't work, even though all the individual "pieces" seem to work on their own (the "if/then" logic works in the datastep outside of the macro, for instance). Any ideas about how to make this work better or help me understand where I'm going wrong would be appreciated.
An example input dataset might look like this:
And the expected output for the above would look like this:
Edited to correct the macro code I've been trying.
Your macro is not generating any lines of SAS code to add to your data step.
You need to replace this macro logic
%if %substr(&field,%length(&field)-&sufflen)=&suff %then &newfield='test';
With some actual SAS code. Probably something like:
if substrn(&field,length(&field)-&sufflen)="&suff" then &newfield='test';
You can turn on the MPRINT option to see in your SAS log the lines of SAS code that your macro generates.
Not use macro loop:
%let suffix =AV AVE AVENUE BEACH BLUFF BLVD BOULEVARD;
data want;
set have;
word=scan(address,-1);
if findw("&suffix",word,' ','RI')>0 then New_address=tranwrd(address,strip(word),'');
else New_address=address;
drop word;
run;

%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.;

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

Transform literal date parameter to SAS date value in macro

I want to create a SAS macro which takes a literal date (eg. '31may2011'd) as parameter. Inside the macro I want to transform this into a SAS date value (eg. 18778).
%macro transLiteralDate2Value(literal=);
%put literal = &literal.;
%put sasdatavalue = ???; /* how to calculate this value ? */
%mend;
%transLiteralDate2Value(literal='31may2011'd);
Is the are elegant way to achieve this? Of course I could do this by parsing the literal string, but I think there must be a better way.
I use SAS 9.1.3
This will work inside or outside of a macro. Don't forget %sysfunc() has a handy optional second parameter which will let you format the output value.
%let report_date = %sysfunc(sum('01JAN2011'd),best.);
or
%let report_date = %sysfunc(putn('01JAN2011'd,best.));
Cheers
Rob
You can do it using the %sysfunc macro function.
%macro transLiteralDate2Value(literal=);
%put literal = &literal.;
%put sasdatavalue = %sysfunc(putn(&literal.,8.));
%mend;
%transLiteralDate2Value(literal='31may2011'd);
It is handy to have a pair of simple conversion macros like mine below. See also my sas-l posting.
%macro date2num(date, informat=anydtdte.);
%*-- strip quotations and postfix d from date literal if any. --*;
%*-- quotations are intentionally doubled to prevent unmatched error --*;
%let date=%sysfunc(prxchange(s/[''""]d?//i,-1,&date));
%sysfunc(inputn(&date,&informat))
%mend date2num;
%macro num2date(num, format=date10., literal=1);
%local n;
%let n = %sysfunc(putn(&num,&format));
%if &literal %then "&n"d; %else &n;
%mend num2date;