SAS:从excel文件一次创建多个数据集

时间:2013-09-03 23:39:33

标签: loops sas

我有一个包含500个股票代码的Excel文件。我希望从一个大的SAS数据集中提取每个股票的回报和其他观察结果。之前,比如20个股票代号,我会做以下几个:

data s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 s17 s18 s19 s20;

set tick;
if stock='DIS' then output s1;
if stock='AA' then output s2; 
if stock='QCOM' then output s3; 
if stock='FB' then output s4; 
if stock='AMGN' then output s5;
if stock='AMZN' then output s6; 
if stock='AXP' then output s7; 
if stock='NWS' then output s8; 
if stock='INTC' then output s9; 
if stock='KRFT' then output s10;
if stock='CB' then output s11; 
if stock='CELG' then output s12; 
if stock='CMCSA' then output s13; 
if stock='COST' then  output s14; 
if stock='CSCO' then output s15;
if stock='YHOO' then output s16; 
if stock='DELL' then output s17; 
if stock='VOD' then output s18; 
if stock='DOW' then output s19; 
if stock='EBAY' then output s20;
run;

其中tick SAS数据集包含整个库存回报。

然后对于每个s1,s2 .... s20我使用循环在20个不同的文件中进行迭代并应用一些额外的SAS代码。

我想避免用500行代码填写我的SAS代码。 if stock='COST' then output s14;如果我需要在每个代码上应用一系列SAS代码。

我有没有办法让SAS循环遍历我的excel文件的每一行,比如它选择第一个自动收录器,创建一个SAS数据集s1然后我将一些SAS代码应用于此{{1}文件,一旦完成,回到循环的顶部,选择我的Excel的第二行(因此第二个自动收录器)并重复该过程?

2 个答案:

答案 0 :(得分:2)

首先,您最好将事物保留在一个数据集中,然后按组进行下游处理。

如果必须,您可以使用如下宏来编写脚本:

%macro split();
proc sql noprint;
select count(distinct stock)
    into :n
    from tick;

select distinct stock
    into :s1 - :s%left(&n)
    from tick;
quit;

data
    %do i=1 %to &n;
    s&i
    %end;
;
set tick;

%do i=1 %to &n;
   if stock = "&&s&i" then output s&i;
%end;
run;
%mend;

%split();

答案 1 :(得分:2)

正如Dom所说,最佳解决方案是使用一个数据集和BY组来执行此操作。

第二个最佳解决方案是对您现有的宏进行编码,如下所示:

%macro dostuff(stock=);
data mystuff/view=mystuff;
set tick;
where stock="&stock.";
run;

... do stuff ...
%mend;

创建一个视图,然后您可以在不必创建物理数据集的情况下用于下游处理 - 它允许您按需创建它,而不是预先创建数据集。如果您在tick上正确索引stock数据集,它应该比创建多个数据集一样快或快,即使它是一个多遍解决方案(因为它是一个视图)。

-Joe