How to sort data using Data step in SAS

时间:2017-12-18 07:21:51

标签: sas datastep

I want to sort data in SAS data step. What exactly I mean is: the work of proc sort should be done in data step. Is there any solution?

3 个答案:

答案 0 :(得分:4)

如果您正在寻找仅限数据步骤的解决方案,则可以使用hash table执行PROC SORT的工作。需要注意的是,你需要足够的记忆才能做到这一点。

如果要进行简单排序,可以使用ordered:'yes'选项加载哈希表并将其输出到新表。默认情况下,ordered:yes将按升序对数据进行排序。您也可以指定descending

简单排序

data _null_;

    /* Sets up PDV without loading the table */
    if(0) then set sashelp.class;

    /* Load sashelp.class into memory ordered by Height. Do not remove duplicates. */
    dcl hash sortit(dataset:'sashelp.class', ordered:'yes', multidata:'yes');

        sortit.defineKey('Height');     * Order by height;
        sortit.defineData(all:'yes');   * Keep all variables in the output dataset;

    sortit.defineDone();

    /* Output to a dataset called class_sorted */
    sortit.Output(dataset:'class_sorted');
run;

<强>去欺骗

要删除重复项,请执行完全相同的操作,但删除multidata选项除外。在下表中,观察结果(8,9)和(15,16)是彼此重复的。意见9和16将被取消。

data _null_;

    /* Sets up PDV without loading the table */
    if(0) then set sashelp.class;

    /* Load sashelp.class into memory ordered by Height. Do not keep duplicates. */
    dcl hash sortit(dataset:'sashelp.class', ordered:'yes');

        sortit.defineKey('Height');     * Order by height;
        sortit.defineData(all:'yes');   * Keep all variables in the output dataset;
    sortit.defineDone();

    /* Output to a dataset called class_sorted */
    sortit.Output(dataset:'class_sorted');
run;

答案 1 :(得分:2)

Stu打败了我,但如果您的数据集包含一个唯一的密钥,并且您可以将整个内容整合到内存中,则可以使用散列排序,例如:

data _null_;
  if 0 then set sashelp.class;
  declare hash h(dataset:"sashelp.class",ordered:"a");
  rc = h.definekey("age","sex","name");
  rc = h.definedata(ALL:'yes');
  rc = h.definedone();
  rc = h.output(dataset:"class_sorted");
  stop;
run;

如果你真的决心避免使用任何内置的排序方法,一种特别愚蠢的方法是将整个数据集加载到一系列临时数组中,使用手工编码算法对数组进行排序,然后再次导出:< / p>

https://codereview.stackexchange.com/questions/79952/quicksort-in-sas-for-sorting-datasets

答案 2 :(得分:1)

有使用proc ds2的解决方案。

/*Just prepare dataset, because DS2 responds with an error on libraries like sashelp. */
data sql_prep;
set sashelp.class;
run;

/*Delete test dataset before ds2 func, to avoid errors*/
proc datasets nodetails nolist;
delete test;
run;

proc ds2;

data test;
   method run();
      set {select * from sql_prep order by Weight};
   end;
enddata;
run;
quit;

有关sashelp libs的ds2错误的更多info

Appendix到ds2 docs,关于ds2中的sql。