Macros 使用SAS宏创建间隔

Macros 使用SAS宏创建间隔,macros,sas,intervals,Macros,Sas,Intervals,我正在上SAS课程,还有一个项目要做。当然,我并不是在寻找确切的答案(尽管那会很好),但如果能朝着正确的方向大力推进,我将不胜感激 问题是要编写一个宏,根据一个人的年龄以年为单位创建年龄组。给出的代码是: data a ; infile in1 ; input name $ age ; if 30 le age < 33 then agegrp = 30 ; else if 33 le age < 36 then agegrp = 33 ; else

我正在上SAS课程,还有一个项目要做。当然,我并不是在寻找确切的答案(尽管那会很好),但如果能朝着正确的方向大力推进,我将不胜感激

问题是要编写一个宏,根据一个人的年龄以年为单位创建年龄组。给出的代码是:

data a ;
   infile in1 ;
   input  name $ age ;

   if 30 le age < 33 then agegrp = 30 ;
   else if 33 le age < 36 then agegrp = 33 ;
   else if 36 le age < 39 then agegrp = 36 ;
   else if 39 le age < 42 then agegrp = 39 ;
   else if 42 le age < 45 then agegrp = 42 ;
   else if 45 le age < 48 then agegrp = 45 ;
   else if 48 le age < 51 then agegrp = 48 ;
   else if 51 le age < 54 then agegrp = 51 ;
   else if 54 le age < 57 then agegrp = 54 ;
   else if 57 le age  then agegrp = 57 ;
数据a;
填充1;
输入姓名$age;
如果30 le年龄<33,则agegrp=30;
否则,如果33 le年龄<36,则agegrp=33;
否则,如果36 le年龄<39,则agegrp=36;
否则,如果39 le年龄<42,则agegrp=39;
否则,如果42 le年龄<45,则agegrp=42;
否则,如果45 le年龄<48,则agegrp=45;
否则,如果48 le年龄<51,则agegrp=48;
否则,如果51 le年龄<54,则agegrp=51;
否则,如果54 le年龄<57,则agegrp=54;
否则,如果年龄为57岁,则agegrp=57;
我的工作是编写一个SAS宏来生成这些if-then/else语句。这是我到目前为止所拥有的。我知道这不会运行,但我想做点什么,让你们看看我能完成这项任务有多远

options ls=78 formdlim=' ' ;

%MACRO CODEIT(start= , stop= , count= , old= , new= );
%let x=&start;
%let y=%eval(&start+&count);

if &start
   %do x=&start+&count %to &stop %by &count ;
      <= &old < &x then &new=&start ;
      %let start=&x ;
      else if &start
   %end ;
<= &old then &new=&start ;

%MEND

data a ;
   input age ;
   datalines;
   30 31 32 33 34 37 
   38 39 39 41 42 45 
   46 46 47 49 50 50 
   52 53 54 55 56 57

%CODEIT(start=30, stop=57, count=3, old=0, new=0);
options ls=78 formdlim='';
%宏CODEIT(开始=,停止=,计数=,旧=,新=);
%让x=&start;
%让y=%eval(&start+&count);
如果&开始
%do x=&start+&count%到&stop%by&count;

您有一些小问题,但(考虑到具体要求)通常会将其记录下来

首先,宏需要在数据步骤内执行。但是,您有数据线,这意味着这无法正常运行-数据线必须是数据步骤的最后一部分

data a;
input age;
<%codeit call>
datalines;
<data>
;;;;
run;
这应该是你的宏

现在,也就是说,没有理由为此使用宏;您可以在一个数据步骤中完成所有这些工作。如果这是一个宏类,那么您可以在
%do
中生成大致相同的代码;您仍然希望在
%do
中包装整个
(您可以使用
&iter.
或迭代变量所使用的任何内容)


在现实生活中,您可以让我发布的do循环没有宏变量(只是硬编码),也可以更有效地使用
select
语句;或者,更好的是,使用一种格式(
proc format
)来实现重新编码。格式确实是最好的选择,因为这正是它们的用途,而且它们不需要新的数据步骤就可以完成。

是否要求它是宏?这通常不是实现这一点的最佳实践。它需要是一个宏。宏应该能够获取人们年龄的数据集,并根据数据中的年龄范围生成不同范围的if-then/else语句。非常感谢您的快速回复。我希望教授至少在开头加上“这是一种可怕的编程实践,但我要求您这样做是为了学习”?:)
do _iter = &start to &stop by &count;
  if _iter. le &old. lt _iter+&count. then &new. = &start.;
end;
if &old. lt &start. then &new.=&start.-&count.;
else if &old. ge &end then &new. = &old.+&count.;