gpt4 book ai didi

sas - 是否可以循环遍历 SAS 数据集?

转载 作者:行者123 更新时间:2023-12-04 02:43:47 25 4
gpt4 key购买 nike

我有 60 个 sas 数据集,其中包含有关消费者个人特征的数据,例如 id, gender, age, amountSpent, ....每个数据集仅显示一个时间段的数据(数据 1 是一月,数据 2 是二月......)。由于大小和其他一些问题,我无法合并它们。

我如何编写一个多循环来遍历每个数据集,进行一些操作并将估计值保存到一个临时文件中。

SAS 没有 for环形。我如何使用 do ?

最佳答案

但是 sas 确实有一个 do while 宏循环。
所以基本上你需要三件事:
1. 在某种程度上,你的数据集列表。
2. 在此列表上循环的宏。
3. 想做的事。

例如,让我们假设您有一个数据集 WORK.DATASET_LIST,其中包含一个变量库(libname)和一个变量成员(数据集名称),用于您要循环遍历的每个数据集。

那么你可以这样做:

%macro loopOverDatasets();
/*imho good practice to declare macro variables of a macro locally*/
%local datasetCount iter inLibref inMember;

/*get number of datasets*/
proc sql noprint;
select count(*)
into :datasetCount
from WORK.DATASET_LIST;
quit;

/*initiate loop*/
%let iter=1;
%do %while (&iter.<= &datasetCount.);
/*get libref and dataset name for dataset you will work on during this iteration*/
data _NULL_;
set WORK.DATASET_LIST (firstobs=&iter. obs=&iter.); *only read 1 record;
*write the libname and dataset name to the macro variables;
call symput("inLibref",strip(libname));
call symput("inMember",strip(member));
*NOTE: i am always mortified by the chance of trailing blanks torpedoing my code, hence the strip function;
run;

/*now you can apply your logic to the dataset*/
data &inLibref..&inMember.; *assuming you want to apply the changes to the dataset itself;
set &inLibref..&inMember.;
/*** INSERT YOUR LOGIC HERE ***/
run;

/*** ANY OTHER PROCS/DATA STEPS ***/
/*just remember to use &inLibref..&inMember. to refer to the current dataset*/

/*increment the iterator of the loop*/
%let iter=%eval(&iter.+1);
%end;
%mend;

/*call the macro*/
%loopOverDatasets()

这就是想法。
也许您想以不同的方式收集数据集列表。例如,包含所有这些的宏变量。在这种情况下,您必须在循环中使用 %scan 函数来选择数据集。
或者,命名中可能存在逻辑,例如,dataset1、dataset2、dataset3...,在这种情况下,您可以简单地使用 &iter。宏变量。

关于sas - 是否可以循环遍历 SAS 数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17984153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com