SAS MACRO循环

时间:2015-06-04 23:54:21

标签: sql sas sas-macro

我正在处理具有以下结构的数据集:

Color    Apple  Orange  Grape  Avocado  Blueberry
Yellow   1      .       .      .        .
Orange   .      1       .      .        . 
Purple   .      .       1      .        1  

我想写一个为每个水果类型创建表的宏,选择值为1的所有颜色(行)。例如,apple TBL_APPLE的表将有4行,如下所示

目前我正在考虑循环遍历行和列。作为第一步,我将所有行和列变量都转换为宏:

    /*rows*/
    proc sql noprint; 
    select count(*) into :Nobs
    from work.fruit;
    select Color into :Attr1-:Attr%left(&Nobs)
    from work.fruit;quit;

    /*columns*/
    proc contents data=work.fruit out=contents noprint; run;
    %let n=&sqlobs;
    proc sql; select name into :fruit1-fruit%left(&n) from contents; quit;

    %macro fruit;
    %do i=1 %to &NObs;
    %do j=1 %to &n;
    proc sql;
    create table tlb_&&fruit&j as
    select *
    from work.fruit
    where &n = &n;
    quit;
    %end;
    %end;
    %mend fruit;
    %fruit;

3 个答案:

答案 0 :(得分:1)

不确定这是否是你想要的东西,但根据我的理解,问题可以解决 简化如下:

%macro fruit( type);    
   data &type ;
   set dataset;
   where &type = 1;
   run;
%mend fruit;

答案 1 :(得分:0)

我首先定义一个执行您想要重复的简单任务的宏:

%macro fruitds(fruit);
data &fruit.(keep=color);
  set fruit;
  where &fruit eq 1;
run;
%mend fruitds;

然后使用数据步骤读取非sashelp.vcolumns的每个列名称的call executeColor宏的列名称

data _null;
  set sashelp.vcolumn;
  call execute(cats('%fruitds(',name,')'));
  where libname eq 'WORK'
    and memname eq 'FRUIT'
    and name ne 'Color';
run;

答案 2 :(得分:0)

%color_fruit;
proc sql;
      select name into:fruit_name separated by ' ' from dictionary.columns
      where libname='WORK' and memname='FRUIT' and upcase(name)^='COLOR';
quit;
%let nums_fruit=%sysfunc(countw(&fruit_name));
%do i=1 %to &nums_fruit;
    %let fruit=%scan(&fruit_name,&i,%str( ));
     data tab_&fruit;
          set fruit(keep=color &fruit);
          if &fruit=1 then output;
       run;
 %end;
 run;
 %mend;