SAS proc通过宏或数组对许多变量进行单变量

时间:2013-10-15 03:55:16

标签: sas

这应该是一个简单的问题,但我没弄明白...... 我想通过proc univariate获得许多变量的均值和中位数,如下所示。手动为平均值添加M_和为所有变量添加中值MD_非常耗时。我想知道是否有任何简单的方法,如阵列这样做?非常感谢!

代码:

data old;
input year type A1 A2 A3 A4 A5;
datalines;
2000    1   1   2   3   4   5
2000    1   2   3   4   5   6
2000    2   3   4   5   6   7
2000    2   4   5   6   7   8
2001    1   5   6   7   8   9
2001    1   6   7   8   9   10
2001    1   7   8   9   10  11
2001    2   8   9   10  11  12
2001    2   9   10  11  12  13
2001    2   10  11  12  13  14
2002    1   11  12  13  14  15
2002    1   12  13  14  15  16
2002    1   13  14  15  16  17
2002    2   14  15  16  17  18
2002    2   15  16  17  18  19
2002    2   16  17  18  19  20
run;

proc univariate data=old noprint;
    var A1 A2 A3 A4 A5;
    by year type;
    output out=new
    mean=M_A1 M_A2 M_A3 M_A4 M_A5
    median=MD_A1 MD_A2 MD_A3 MD_A4 MD_A5;
run;

预期演示代码:

%let varlist = A1 A2 A3 A4 A5; 
array vars (*) &varlist;
proc univariate data=old noprint;
    var &vars(*);
    by year type;
    output out=new
    mean=M_&vars(*)
    median=MD_&vars(*);
run;

使用proc sql

更正代码
%macro uni;
%let varlist='A1','A2','A3','A4','A5';
%let vars=A1 A2 A3 A4 A5;
proc sql;
select cats('M_',name) into :meannamelist separated by ' '
 from dictionary.columns
 where libname='WORK' and memname='OLD' and name in (&varlist);
select cats('MD_',name) into :mediannamelist separated by ' '
 from dictionary.columns
 where libname='WORK' and memname='OLD' and name in (&varlist);
quit;

proc univariate data=old;
    var &vars;
    by year type;
    output out=new
    mean=&meannamelist
    median=&mediannamelist;
run;
%mend uni;
options mprint;
%uni;

3 个答案:

答案 0 :(得分:2)

另一种选择是在PROC SQL中创建这些列表。

%let varlist=A1,A2,A3,A4,A5;
proc sql;
select cats('M_',name) into :meannamelist separated by ' '
 from dictionary.columns
 where libname='WORK' and memname='OLD' and name in (&varlist);
select cats('MD_',name) into :mediannamelist separated by ' '
 from dictionary.columns
 where libname='WORK' and memname='OLD' and name in (&varlist);
quit;

proc univariate etc.;
mean &meannamelist;
median &mediannamelist;
run;

答案 1 :(得分:1)

完成代码的一种方法是遍历列表:

proc univariate data=old noprint;

  var

  %let varlist1 = A1 A2 A3 A4 A5;
  %let count_number1=1;
  %let value1=%scan(&varlist1.,&count_number1.); 
  %do %while(&value1. NE %str());

   &value1.

   %let count_number1=%eval(&count_number1.+1);
   %let value1=%scan(&varlist1.,&count_number1.);
  %end;
   ;

  by year type;
  output out=new
  mean=

   %let varlist2 = A1 A2 A3 A4 A5;
   %let count_number2=1;
   %let value2=%scan(&varlist2.,&count_number2.); 
    %do %while(&value2. NE %str());

       M_&value2. 

       %let count_number2=%eval(&count_number2.+1);
       %let value2=%scan(&varlist2.,&count_number2.);
     %end;
    ;
run;

答案 2 :(得分:0)

如果您可以使用PROC MEANS获取所需的统计信息,请执行此操作;它在输出语句中有一个autoname选项,大致可以满足您的要求。均值和中位数均可在PROC MEANS中找到。

如果没有,您可以查看ods output来简化操作。