根据宏变量值复制/重命名多个sas数据集

时间:2016-08-12 15:59:01

标签: sas sas-macro datastep

我有一个宏变量&myfiles,其中包含四个数据集名称的列表。

%put &myfiles;
cpo.CDR_2016jun cpo.Cog_2016jun cpo.Mile_2016jun cpo.Path_2016jun

cpo是libname。

我正在尝试创建四个新数据集,其名称来自另一个我命名为&New_Datasets的宏变量:

%put &New_Datasets;
CDR Cog Mile Path

我尝试使用这样的数据步骤:

data &New_Datasets;
     set &myfiles;
run;

但是这导致&mylist中引用的四个数据集的所有观察结果被合并并放入&New_Datasets中引用的四个数据集中的每一个中,日志的输出如下:

NOTE: There were 1482 observations read from the data set CPO.CDR_2016JUN.
NOTE: There were 1444 observations read from the data set CPO.COG_2016JUN.
NOTE: There were 255 observations read from the data set CPO.MILE_2016JUN.
NOTE: There were 7 observations read from the data set CPO.PATH_2016JUN.
NOTE: The data set WORK.CDR has 3188 observations and 1580 variables.
NOTE: The data set WORK.COG has 3188 observations and 1580 variables.
NOTE: The data set WORK.MILE has 3188 observations and 1580 variables.
NOTE: The data set WORK.PATH has 3188 observations and 1580 variables.

我想要完成的是让来自cpo.cdr_2016jun的1482个观测值创建一个数据集work.cdr,其中有1482个观测值,依此类推,而不是让每个新数据集都是set语句中引用的那些。非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:3)

我会稍微不同地定义我的宏变量,并执行以下操作:

%let oldnames = CDR_2016jun Cog_2016jun Mile_2016jun Path_2016jun;
%let newnames = CDR Cog Mile Path;

proc datasets lib = cpo noprint;
    copy out = work;
    select &oldnames;
    run;
quit;

%macro changes;
%local i;
%do i = 1 %to %sysfunc(countw(&oldnames));
    %scan(&oldnames, &i, %str( )) = %scan(&newnames, &i, %str( ))
%end;
%mend changes;

proc datasets lib = work noprint;
    change %changes;
    run;
quit;

或者,您可以在work中的原始数据集的cpo中创建视图。

答案 1 :(得分:2)

您必须编写一个宏程序,循环遍历宏变量中的值并调用数据步骤或proc复制。

<强>宏:

%macro rewriteDataSets(source_tables=, dest_tables=);
   %local ii num_source_tables num_dest_tables source_name dest_name;

   %let num_source_tables = %sysfunc(countw(&source_tables, %str( )));
   %let num_dest_tables   = %sysfunc(countw(&dest_tables  , %str( )));

   %if &num_source_tables ne &num_dest_tables %then %do;
      %put ERROR: The number of source and destination tables must be the same in the call to rewriteDataSets;
      %abort cancel;
   %end;

   %do ii=1 %to &num_source_tables;

      %let source_name = %scan(&source_tables, &ii, %str( ));
      %let dest_name   = %scan(&dest_tables  , &ii, %str( ));

      data &dest_name;
        set &source_name;
      run;

   %end;
%mend rewriteDataSets;

使用示例:

%rewriteDataSets(source_tables = sashelp.class sashelp.class,
                 dest_tables   = a b);

或者使用您指定的表格,您可以这样称呼它:

%rewriteDataSets(source_tables = cpo.CDR_2016jun cpo.Cog_2016jun cpo.Mile_2016jun cpo.Path_2016jun,
                 dest_tables   = CDR Cog Mile Path);

或使用proc copy代替数据步骤。