【问题标题】:How do you print the last observation of a SAS data set?如何打印 SAS 数据集的最后一次观察?
【发布时间】:2011-10-31 17:16:07
【问题描述】:

我有一个包含 1000 个观察值的数据集。我只想打印出最后的观察结果。使用以下内容:

proc print data=apple(firstobs = 1000 obs = 1000); 
run;

我可以得到最后的观察结果。但我必须提前知道我的数据集有 1000 个观察值。在不知道的情况下如何做到这一点?

【问题讨论】:

  • 嗨,特雷弗,“如何获取数据集中的观察次数”的问题已在此处得到解答:stackoverflow.com/questions/5658994/…
  • 提醒任何正在学习 SAS Base 测试并最终来到这里的人——不要中了他们的把戏——没有 LASTOBS 选项这样的东西! :)

标签: sas


【解决方案1】:

有很多方法可以做到这一点。这里有两个:

proc sql noprint;
 select n(var1) into :nobs
 from apple;
quit;

proc print data=apple(firstobs=&nobs); run;

这只是将观察的数量读入一个宏变量,然后用它来指定第一个观察。 (请注意,var1 指的是数据中的一个变量。)

另一种方法是创建一个仅保留最后一个观察结果的数据视图,然后将其打印出来:

data tmp / view=tmp;
 set apple nobs=nobs;
 if _n_=nobs;
run;

proc print data=tmp; run;

【讨论】:

    【解决方案2】:

    我认为SETMERGEMODIFYUPDATE 语句的end 选项非常有用。

    data x;
      do i = 1 to 1000;
        output;
      end;
    run;
    
    data x;
      set x end = _end;
      end = _end;
    proc print data = x;
      where end;
    run;
    

    【讨论】:

      【解决方案3】:

      有很多方法可以找到观察次数;下面的宏就是一个例子。

      %macro nobs (dsn);
         %let nobs=0;
         %let dsid = %sysfunc(open(&dsn));
         %if &dsid %then %let nobs = %sysfunc(attrn(&dsid,nobs));
         %let rc   = %sysfunc(close(&dsid));
         &nobs
      %mend nobs;
      
      %let n = %nobs(apple);
      
      proc print data=apple (firstobs=&n obs=&n); run;
      

      【讨论】:

        【解决方案4】:

        有两种简单的解决方案:

        解决方案 1:

        data result;
            set apple end=end;
            if end then output;
        run;
        proc print data=result;
        run;
        

        解决方案 2:

        data result;
            set apple nobs=nobs;
            if _N_=nobs then output;
        run;
        proc print data=result;
        run;
        

        【讨论】:

          猜你喜欢
          • 2013-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-16
          • 2015-12-14
          • 1970-01-01
          相关资源
          最近更新 更多