在引用宏之外的全局宏变量以创建新数据集时遇到了一些麻烦。创建全局变量是为了运行循环,以使用指定年份的向量创建多个年度数据集,如下面的代码所示:
%macro loopyear;
%global year;
%do year = 2004 %to 2017;
proc import datafile = "C:\Filepath\blah.txt"
dbms = dlm out = blah&year.; /*Creates a dataset for each year, e.g. blah2004, blah2005, etc.) */
delimiter = " ";
getnames = no;
run;
data blah&year.;
set blah&year.;
year = &year.;
run;
proc sql;
create table blah&year._rail as
select year, var1, var2, var3, var4
from blah&year.
where var2= "rail";
quit;
%end;
%mend loopyear;
%loopyear;
/*Merge all year datasets into one master set*/
data blah_total;
set blah&year._rail;
run;
但是,当我尝试在宏之外创建主数据集时,出现以下错误:
data blah;
set blah&year._rail;
run;
ERROR: File work.blah2018_rail.data does not exist
这令人沮丧,因为我仅尝试基于宏变量中引用的2004-2017年数据创建母版集。有人可以帮助我查明我的错误吗-是我定义全局变量的方式,还是我错过了某个步骤?任何帮助表示赞赏。
谢谢!
答案 0 :(得分:0)
这是SAS中宏和数据步骤do-loop的一个有趣的怪癖-循环计数器在检查退出条件之前递增,因此在循环运行之后,它将比停止值高1个增量,例如:
%macro example;
%do i = 1 %to 3;
%put i = &i;
%end;
%put i = &i;
%mend;
%example;
输出:
i = 1
i = 2
i = 3
i = 4
对于最后一步,您可能希望set语句看起来像这样:
set blah2004_rail ... blah2017_rail;
您可以编写一个宏循环来生成列表,并将数据步骤移至宏内,例如
set %do year = 2004 %to 2017; blah&year._rail %end;;
第二个分号很重要!您需要一个来关闭%end
,并需要一个来终止set语句。
答案 1 :(得分:0)
更改您的命名结构。有一个通用的前缀,并在年份的末尾加上年份,那么您可以使用分号一次简短地引用所有数据集。
%macro loopyear;
%global year;
%do year = 2004 %to 2017;
proc import datafile = "C:\Filepath\blah.txt"
dbms = dlm out = blah&year.; /*Creates a dataset for each year, e.g. blah2004, blah2005, etc.) */
delimiter = " ";
getnames = no;
run;
data blah&year.;
set blah&year.;
year = &year.;
run;
proc sql;
create table blah_rail_&year. as
select year, var1, var2, var3, var4
from blah&year.
where var2= "rail";
quit;
%end;
%mend loopyear;
%loopyear;
/*Merge all year datasets into one master set*/
data blah_total;
set blah_rail: ;
run;