6

I have a data set with 1000 observations. I want to only print out the last observation. Using the following:

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

I can get the last observation. But I have to know in advance that my data set has 1000 observations. How do I do this without knowing this?

Triad sou.
  • 2,969
  • 3
  • 23
  • 27
NebulousReveal
  • 562
  • 2
  • 7
  • 19
  • 2
    Hi Trevor, the question "how to get the number of observations in a dataset" has been answered here: http://stackoverflow.com/questions/5658994/how-to-detect-whether-a-data-set-has-no-observations-in-sas – Robert Penridge Oct 31 '11 at 22:41
  • a heads up for anyone who is studying for the SAS Base test and ended up here -- don't fall for their tricks -- there is no such thing as a LASTOBS option! :) – tumultous_rooster Mar 18 '14 at 03:32

4 Answers4

7

There are many ways you could do this. Here are two:

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

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

This just reads the number of observations into a macro variable, and then use that to specify the first observation. (Note that var1 refers to a variable in your data.)

Another approach would be to create a data view that only keeps the last observation and then print that:

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

proc print data=tmp; run;
itzy
  • 11,275
  • 15
  • 63
  • 96
3

I think that the end option for the SET, MERGE, MODIFY, or UPDATE statement is very useful.

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;
Triad sou.
  • 2,969
  • 3
  • 23
  • 27
1

There are two simple solutions:

Solution 1:

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

Solution 2:

data result;
    set apple nobs=nobs;
    if _N_=nobs then output;
run;
proc print data=result;
run;
gaofangshu
  • 41
  • 1
  • 6
1

There are many ways to find the number of observations; the following macro is one example.

%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;
RWill
  • 939
  • 5
  • 6