我有超过3400个CSV文件,大小在10kb到3mb之间变化。每个CSV文件都有这个通用文件名:stockticker-Ret.csv
其中stockticker
是AAPL,GOOG,YHOO等股票代码,并且在给定日期的每分钟都有股票回报。我的SAS代码首先从加载SAS数据集中stockticker-Ret.csv
文件的所有股票代码名称开始。我遍历每个自动收报机,在名为.csv
的SAS数据集中加载相应的want
文件,并在want
上应用一些数据,并将每个自动收报机的最终数据集want
存储在SAS数据集名为global
。可以想象,这个过程需要很长时间。有没有办法改进我的DO LOOP
代码,使这个过程更快?
/*Record in a sas dataset all the csv file name to extract the stock ticker*/
data yfiles;
keep filename;
length fref $8 filename $80;
rc = filename(fref, 'F:\data\');
if rc = 0 then do; did = dopen(fref);
rc = filename(fref); end; else do; length msg $200.; msg = sysmsg(); put msg=; did = .; end;
if did <= 0 then putlog 'ERR' 'OR: Unable to open directory.';
dnum = dnum(did);
do i = 1 to dnum; filename = dread(did, i); /* If this entry is a file, then output. */ fid = mopen(did, filename); if fid > 0 then output; end;
rc = dclose(did);
run;
/*store in yfiles all the stock tickers*/
data yfiles(drop=filename1 rename=(filename1=stock));
set yfiles;
filename1=tranwrd(filename,'-Ret.csv','');
run;
proc sql noprint;
select stock into :name separated by '*' from work.yfiles;
%let count2 = &sqlobs;
quit;
*Create the template of the desired GLOBAL SAS dataset;
proc sql;
create table global
(stock char(8), time_gap num(5), avg_ret num(5));
quit;
proc sql;
insert into global
(stock, time_gap,avg_ret)
values('',0,0);
quit;
%macro y1;
%do i = 1 %to &count2;
%let j = %scan(&name,&i,*);
proc import out = want datafile="F:\data\&j-Ret.csv"
dbms=csv replace;
getnames = yes;
run;
data want;
set want; ....
....[Here I do 5 Datasteps on the WANT sasfile]
/*Store the want file in a global SAS dataset that will contain all the stock tickers from the want file*/
data global;
set global want; run;
%end;
%mend y1;
%y1()
正如您所见,全局SAS数据集针对我存储在want
中的每个global
数据集进行了扩展。
答案 0 :(得分:4)
假设文件具有公共布局,则不应使用PROC IMPORT
或do循环导入它们。你应该用一个datastep读取它们。 IE:
data want;
length the_file $500;
infile "f:\data\*.csv" dlm=',' lrecl=32767 dsd truncover firstobs=2 filename=the_file;
input
myvar1 myvar2 myvar3 myvar4;
stock_ticker=scan(the_file,'\',-1); *or whatever gets you the ticker name;
run;
现在,如果它们没有相同的布局,或者readin有一些复杂性,您可能需要一个比这更复杂的输入语句,但几乎总是可以通过这种方式实现它。由于IMPORT的开销,具有大量PROC IMPORT的循环总是效率低下。
如果您不希望文件夹中的每个.csv文件(并且无法为您想要的内容编写掩码),或者如果您有布局的子集,则可以使用FILEVAR选项来读取文件来自一个共同的数据集。然后,如果需要,您可以分支到各种输入语句中。
data want;
set yfiles;
infile a filevar=filename;
if filevar [some rule] then do;
input ... ;
end
;else if ... then do;
input ... ;
end;
run;