DATA Step, Macro, Functions and more

getting last observation from a dataset

Reply
N/A
Posts: 0

getting last observation from a dataset

Hi

is there any option to get last observation in a dataset( using firstobs , obs dataset options)

ex:
data ex;
input a;
datalines;
66
77
88
;

output:
88
N/A
Posts: 0

Re: getting last observation from a dataset

This would be the syntax, however it will not work when data is read from datalines. It will work when reading from a file, and if you put it on a set statement for a dataset:


data ex;
infile datalines END=LAST;
input a;
IF LAST;
datalines;
66
77
88
;
N/A
Posts: 0

Re: getting last observation from a dataset

thank u very much.

is there any possibility using with firstobs, obs dataset options for creating that dataset.
Super Contributor
Super Contributor
Posts: 3,174

Re: getting last observation from a dataset

In SAS 9.1.3, the SET stmt FIRSTOBS=MAX parameter generates an error, unfortunately, for what appears to be an incorrect "last observation" calculation (based on the error message).


Scott Barry
SBBWorks, Inc.


data x;
do i=1 to 21;
output;
end;
stop;
run;
data _null_;
set x (firstobs=max);
putlog _all_;
stop;
run;
Contributor
Posts: 61

Re: getting last observation from a dataset

Hi SaiRam,

If u know the number of Observations(firstobs or obs).

Try this.,

data test;
infile cards
firstobs=3;
input a;
cards;
76
56
98
;
proc print;
run;

Venky.
Occasional Contributor BPD
Occasional Contributor
Posts: 12

Re: getting last observation from a dataset

Sairam,

The following utility macro might solve your problem:

%MACRO obs(lib=,mem=);
%LET ds = %SYSFUNC(OPEN(&lib..&mem));
%LET noobs = %SYSFUNC(ATTRN(&ds,NOBS));
%LET ds = %SYSFUNC(CLOSE(&ds));
&noobs;
%MEND obs;

If we generate the following dataset - a1

data a1;
do val = 1 to 100;
output;
end;
run;

Use the macro statement - %LET to assign a macro variable (obs_in_dset in this example) the output of the %obs macro. In the macro call name the sas library in which your dataset resides (lib=work) and the sas dataset name (mem=a1)

e.g.
%let obs_in_dset = %obs(lib=work,mem=a1);

Now when you want to read the last obs in the a1 dataset use

data lastina1;
set a1(firstobs=&obs_in_dset);
run;

I hope you find this useful.

Regards,

BPD
N/A
Posts: 0

Re: getting last observation from a dataset

when your data are in a SAS data set, you can point read the last row (without reading the other rows):[pre] data last_row ;
set your_dataset nobs=nobs point= nobs;
output ;
stop ;
run ;[/pre]

was that what was wanted?


PeterC
Contributor
Posts: 63

Re: getting last observation from a dataset

_Exactly_ what I needed. Thanks PeterC wherever you are.
Ask a Question
Discussion stats
  • 7 replies
  • 343 views
  • 0 likes
  • 5 in conversation