我对SAS很新,我正在寻找一些指导。 我有两张桌子。一个包含我的数据(类似下面的内容,虽然大得多):
Data DataTable;
Input Var001 $ Var002;
Datalines;
000 050
063 052
015 017
997 035;
run;
我的变量是从000到999的整数(以文本形式读入)。根据用户的行为,可能只有两个,或多达500个。
第二个表包含DataTable中用户指定的变量分组:
Data Var_Groupings;
input var $ range $ Group_Desc $;
Datalines;
001 025 0-25
001 075 26-75
001 999 76-999
002 030 0-30
002 050 31-50
002 060 51-60
002 999 61-999;
run;
(实际上,此表在excel中由用户调整然后导入,但这将用于故障排除)。
var_groupings表中的“var”变量对应于DataTable中的var列。因此,例如var_groupings表中的“var”为001表示该分组将在DataTable的var001上。
“Range”变量指定分组的上限。因此,查看var_grouping表中var等于001的范围,用户希望第一组从0到25,第二组从26到75,最后一组从76到999。 / p>
编辑:Group_Desc列可以包含任何字符串,但不一定是此处显示的格式。
决赛桌应该是这样的:
Var001 Var002 Var001_Group Var002_group
000 050 0-25 31-50
063 052 26-75 51-60
015 017 0-25 0-30
997 035 76-999 31-50
我不确定我怎么会这样做。您将给予的任何指导将不胜感激。
答案 0 :(得分:1)
这是一个有趣的,谢谢!它可以使用CALL EXECUTE来解决,因为我们需要从值创建变量名。显然,PROC FORMAT是将一些值转换为范围的最简单方法。所以,结合这两件事,我们可以做到这样的事情:
proc sort data=Var_Groupings; by var range; run;
/*create dataset which will be the source of our formats' descriptions*/
data formatset;
set Var_Groupings;
by var;
fmtname='myformat';
type='n';
label=Group_Desc;
start=input(lag(range),8.)+1;
end=input(range,8.);
if FIRST.var then start=0;
drop range Group_Desc;
run;
/*put the raw data into new one, which we'll change to get what we want (just to avoid
changing the raw one)*/
data want;
set Datatable;
run;
/*now we iterate through all distinct variable numbers. A soon as we find new number
we generate with CALL EXECUTE three steps: PROC FORMAT, DATA-step to apply this format
to a specific variable, and then PROC CATALOG to delete format*/
data _null_;
set formatset;
by var;
if FIRST.var then do;
call execute(cats("proc format library=work cntlin=formatset(where=(var='",var,"')); run;"));
call execute("data want;");
call execute("set want;");
call execute(cats('_Var',var,'=input(var',var,',8.);'));
call execute(cats('Var',var,'_Group=put(_Var',var,',myformat.);'));
call execute("drop _:;");
call execute("proc catalog catalog=work.formats; delete myformat.format; run;");
end;
run;
<强>更新即可。我已经更改了第一个DATA步骤(用于创建格式集),因此现在每个范围的结束和开始都来自变量range
,而不是Group_Desc
。 PROC SORT移到了代码的开头。