【问题标题】:Using SAS sql to create macro variables使用 SAS sql 创建宏变量
【发布时间】:2013-01-23 09:28:08
【问题描述】:

我正在使用 SAS sql 创建一些宏变量以供以后使用和打印报告。

我正在按组创建一些汇总变量(平均值、最小值、最大值等)。

以下代码适用于第一组,但不会为第二组和第三组创建宏变量。


data scores;
  input trt  t;
cards;  
1  10
1  11
1  12
1  13
2  4
2  5
2  6
2  7
3  9
3  8
3  7
3  6
;
run;



%macro cdi;


%do i = 1 %to 3;

proc sql noprint;
  select  n(t),  nmiss(t),  mean(t),  std(t),  min(t),  max(t) 
    into  :n&i,   :miss&i,  :mean&i,   :sd&i,  :min&i,  :max&i

  from scores
  where trt = &i;
quit;

%end;

%mend cdi;
%cdi;

*****  this call shows the right values  ;
%put &n1 &miss1 &mean1 &sd1 &min1 &max1 ;


*****  this call produces error (symbolic reference not resolved)  ;
%put &n2 &miss2 &mean2 &sd2 &min2 &max2 ;

我确定我错过了一些简单的东西,但我还没有看到它......

【问题讨论】:

    标签: sql macros sas


    【解决方案1】:

    您的问题是您正在创建的宏变量是宏的本地变量。如果希望 then 在宏执行后存在,则需要在宏内部使用%global 语句定义它们。

    换句话说,将其添加到宏定义的顶部:

    %global n1 miss1 mean1 sd1 min1 max1 
            n2 miss2 mean2 sd2 min2 max2 
            n3 miss3 mean3 sd3 min3 max3 ;
    

    【讨论】:

    • @blueandgrey 比摇滚明星更像个老屁。看到你的个人资料;大约 15 岁。以前,我为 UI Spine Center 做了一些 SAS 编程,但我仍然带着我的巨型纪念品咖啡杯,每当爱荷华州击败密歇根州以惹恼同事时,我都会带着它去上班。所以去鹰眼!
    • 没错!去老鹰队!除非我们被密歇根和明尼苏达击败,而且……嗯……
    【解决方案2】:

    鲍勃是正确的。解决方法很简单,就是剪切粘贴:

    %macro cdi;
    
    
    %do i = 1 %to 3;
    
    proc sql noprint;
      select  n(t),  nmiss(t),  mean(t),  std(t),  min(t),  max(t) 
        into  :n&i,   :miss&i,  :mean&i,   :sd&i,  :min&i,  :max&i
    
      from scores
      where trt = &i;
    quit;
    
    %end;
    *****  this call shows the right values  ;
    %put &n1 &miss1 &mean1 &sd1 &min1 &max1 ;
    
    
    *****  this call NO LONGER produces error (symbolic reference not resolved)  ;
    %put &n2 &miss2 &mean2 &sd2 &min2 &max2 ;
    
    %mend cdi;
    %cdi;
    

    【讨论】:

    • 这对解决问题没有任何作用,尽管它确实说明了范围界定问题。
    • 啊,抱歉应该仔细阅读。以为他只是想打印日志。
    【解决方案3】:

    为什么要创建汇总值的宏变量?确实很少有使用情况,最好将其创建为表以供以后使用……而且它更快、更简单、更灵活。

    proc sql;
    create table summary as
    select  trt, n(t) as n,  nmiss(t) as nmiss,  mean(t) as mean,  std(t) as std,  min(t) as min,  max(t) as max
    from scores
    group by trt;
    quit;
    

    或者,既然你在 SAS...

    proc means data=scores;
    var t;
    class trt;
    types trt;
    output out=summary n= nmiss= mean= std= min= max= /autoname;
    run;
    

    然后根据需要在报告中使用它 - 或者将其合并回主数据集,如果这样更容易的话。数据应该是数据,宏变量不应该是数据,而是程序输入。

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多