NebulousReveal
NebulousReveal

Reputation: 572

How do you print the last observation of a SAS data set?

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?

Upvotes: 6

Views: 29177

Answers (4)

gaofangshu
gaofangshu

Reputation: 41

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;

Upvotes: 1

Triad sou.
Triad sou.

Reputation: 2971

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;

Upvotes: 3

RWill
RWill

Reputation: 949

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;

Upvotes: 1

itzy
itzy

Reputation: 11755

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;

Upvotes: 7

Related Questions