在编写宏程序的时候遇到一个问题,即一个宏变量与其它字母、数字按一定的规则组合成为另一个宏变量,比如
%let mvar = group;
%let &mvar.1 = A;
即上面这条语句定义了一个新的宏变量:group1,值是A,那么这个宏变量如何在程序中调用呢?
在SAS的网站上检索到一篇文献(地址:http://www2.sas.com/proceedings/sugi22/CODERS/PAPER77.PDF),其中有一段:“The macro variable &DSN&N resolves to CLINICS5, &DSN5 resolves to FRED. The &&DSN&N combination first resolves to a macro variable (&DSN5) which then resolves to a value (FRED) in a second pass. ” 按照这篇文献,上面的问题很简单:引用宏变量group1写成&&mvar.1即可,但在SAS9中,实践证明这样的写法无法解析成为&group1。
后来在人大经济论坛里找到了这个问题的答案:&&&mvar.1。
之后又检索了一篇文章,专门是写这个&&&&&......解析问题的:http://www.listserv.uga.edu/cgi-bin/wa?A2=ind0706b&L=sas-l&P=43316
主要内容如下:
--------------------------------
Consider:
%let a=b; /* n=1 */
%let b=c; /* n=2 */
%let c=d; /* n=3 */
%let d=e; /* n=4 */
Problem: Give the value of D in terms of A.
&d is e
&c is d so &&&c is e
&b is c so &&&b is d so &&&&&&&b is e
&a is b so &&&a is c so &&&&&&&a is d so &&&&&&&&&&&&&&&a is e
General rule:
Two &'s resolve to 1 and the expression is re-scanned.
Corr:
2**n - 1 &'s needed
Now that we have the base of understanding, here is the code.
%macro q ( n=1 ) ; %local i ampers m ; %do i = 1 %to &n ; %local x&i ; %let x&i = x%eval(&i+1) ; %put x&i = x%eval(&i+1) ; %end ;
%let m = %eval(2**&n-1); %let ampers = %qsysfunc(repeat(%nrstr(&),&m-1)) ; %put amperlen=%length(&ers) ; %put %superq(ampers)x1 = >>>%unquote(&ers.x1)<<< ; %mend q ;
%q(n=15)
Don't try to go above 15 because the number of ampersands is too great to hold in a "text expression" in the macro language.
Is this an important program? No, but any macro programmer should know how to manipulate ampersands and how they are resolved, so it is an important question to ask for understanding.
On the other hand, in my first macro class I asked the students to derive the corollary from the general principle. I soon learned that programmers don't count above 3.
A search for "multiple ampersands" at http://lexjansen.com/sugi/ turned up 67 papers, many of which look relevant to some degree.
--------------------------------
原来,多个&解析的规则是2**n - 1,对于最开始的那个问题,n=2,则需要&&&才能解析为我们要的宏变量。










留个言,我也关注sas在医学领域的应用,http://blog.sina.com.cn/asteriod2008 能交换个链接吗?