【问题标题】:How to print the first 10 and last 10 observations in SAS?如何在 SAS 中打印前 10 个和后 10 个观察值?
【发布时间】:2018-02-26 03:29:00
【问题描述】:

我正在尝试找到一种仅打印我的 SAS 数据集的前 10 个和最后 10 个观察值的方法。有没有办法做到这一点?

我试过proc print data = ia.usage; where Obs < 10 & Obs > 80;run; 但该命令仍会打印出所有 90 个观察值。关于如何轻松做到这一点的任何想法?

谢谢。

【问题讨论】:

    标签: sas statistics


    【解决方案1】:

    获得前 10 名很容易:

    /*First 10 obs*/
    proc print data = ia.usage(obs = 10); run;
    

    获得最后 10 名有点困难,但这可以使用视图来完成:

    /*Last 10 obs*/
    data last10 /view = last10;
      startobs = nobs - 9;
      set ia.usage nobs = nobs firstobs = startobs;
      drop startobs;
    run;
    proc print data = last10; run;
    

    如果您希望两者都在同一个 proc 打印中,您可以创建两个视图并将它们组合到另一个视图中,然后打印它:

    data first10 /view = first10;
      set ia.usage(obs = 10);
    run;
    
    data first10_last10 /view = first10_last10;
      set first10 last10;
    run;
    
    proc print data = first10_last10; run;
    

    即使对于大型数据集,上述方法也应该非常快,但它假设您的初始数据集不是视图,因为它依赖于知道数据集中的行数(nobs)。如果您有视图,则需要通读整个数据集以找出行数,然后再次读取,丢弃除第一行和最后 10 行之外的所有内容。这会慢很多。例如

    data first10_last10 /view = first10_last10;
      do nobs = 1 by 1 until(eof);
        set ia.usage(drop = _all_) end = eof; /*We only want the row count, so drop all vars on this pass to save a bit of time*/
      end;
      do _n_ = 1 to nobs;
        set ia.usage;
        if _n_ <= 10 or _n_ >= nobs - 9 then output;
      end;
    run;
    
    proc print data = first10_last10;
    

    【讨论】:

      【解决方案2】:

      这可以使用单个视图来实现:

      data want/view=want;
        set ia.usage nobs=__nobs;
        if _n_ le 10 or _n_ gt __nobs-10;
      run;
      
      proc print data=want;
      run;
      

      【讨论】:

      • 这对于大型数据集可能会很慢,因为它涉及读取整个数据集,而不仅仅是前/后 10 行。
      • 是的,同意,你提交的方法效率更高
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 2013-04-28
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多