我正在使用SAS 9.3对几个CSV数据集进行一些分析。 我希望自动加载对SAS说的文件 查看特定目录并加载到每个文件的单独数据集。
我是SAS编码的新手,所以如果我忽略了一些关于它的重要观点,请原谅我。
我要使用的代码就像这样:
filename filelist pipe 'dir "C:\my_path\*.csv" /b';
data file_list ; *** here I have the list of files to be read
length file_name $256 ;
infile filelist length=reclen ;
input file_name $varying256. reclen ;
run;
*** HERE I MISS HOW TO DYNAMICALLY LOAD A NUMBER OF FILES NOT KNOWN BEFORE;
*** I should find a way to say: set file_list;
proc import datafile="C:\my_path\"||file_name; *** I know that in this way doesn't work but It was just to show my idea of doing it.
out = file_name
dbms = csv
replace;
getnames = yes;
run;
非常感谢你的帮助! 请随时完全编辑解决此任务的方法。
收到建议后,我修改了代码,但仍然没有工作......
filename filelist pipe 'dir "C:\my_path\*.csv" /b';
data file_list ; *** here I have the list of files to be read
length file_name $256 ;
infile filelist length=reclen ;
input file_name $varying256. reclen ;
run;
%MACRO load_my_csv_file(name_file=);
proc import datafile="C:\my_path\"||&name_file
out = &name_file
dbms = csv
replace;
getnames = yes;
run;
%MEND load_my_csv_file;
data _NULL_ ;
set file_list;
call execute('%load_my_csv_file(name_file='||file_name||')');
run;
但它不起作用!
答案 0 :(得分:1)
使用DATAFILE和OUT参数将PROC导入到宏中。然后使用数据FILE_LIST中的CALL EXECUTE调用它。
答案 1 :(得分:0)
试试这个:
/*get the filepath of the folder you want to import from*/
%let folderpath = your_file_path;
filename files pipe "%str(dir %"&folderpath.%" /B) " lrecl=5000;
/*create a dataset containing the names of all the files in that directory*/
data list_of_files;
infile files truncover;
input file $255.;
run;
/*select those into a macro variable to loop through*/
proc sql noprint;
select distinct file into: files_to_import
separated by " "
from list_of_files;
quit;
/*loop through the macro variable and import all the files*/
%macro csv_importer;
%do i = 1 %to %sysfunc(countw(&files_to_import.));
%let this_file = %scan(&files_to_import., &i., " ");
proc import datafile = "&folderpath.\&this_file."
out = dataset&i.
dbms = csv replace;
getnames = yes;
run;
%end;
%mend csv_importer;
%csv_importer;
答案 2 :(得分:0)
您没有在宏内部正确使用参数值来生成有效的SAS语法。您不能在过程选项的值内使用连接运算符(||
)。而是在适当的位置扩展宏变量的值,以便生成的代码是过程的有效语法。此外,您可能会发现需要向宏添加另一个参数来处理物理文件名不是用于SAS数据集的有效名称的情况。例如,您的文件名可能以.csv
结尾,但您不希望在SAS数据集的名称中包含.csv
。
%MACRO load_my_csv_file(name_file=,dsname=);
proc import datafile="C:\my_path\&name_file"
out = &dsname
dbms = csv
replace
;
getnames = yes;
run;
%MEND load_my_csv_file;
然后你可以用:
来调用它data _NULL_ ;
set file_list;
dsname = scan(file_name,-2,'./\');
call execute(cats('%load_my_csv_file(name_file=',file_name,',dsname=',dsname,')'));
run;