AS known to us, _n_ can be used in IF-Then statement for manipulation for any speciifed observation when the observation number is known. How to do the same thing for last observation since we do not know it's obervation number
Editor's note: this is a very popular question. To help others to find the answer, we have consolidated the most helpful answers into this one reply as an Accepted Solution.
or ...
/* Simple approach */
data last;
/* get number of records (N) */
if 0 then
set sashelp.class nobs=nobs end=eof;
/* use POINT= to get nth record */
set sashelp.class point=nobs;
output;
stop;
run;
More robust approach from @data_null__:
/* Create sample data */
data class;
set sashelp.class;
run;
data class;
modify class end=eof;
/* uncomment this to create empty set for test */
*remove;
if eof or ranuni(12344) lt .2 then
remove;
run;
/* print all records */
proc print;
run;
/* find last record, handle empty sets */
data last;
if eof then
stop;
do _n_ = nobs to 1 by -1 until(_error_ eq 0);
_error_ = 0;
set class point=_n_ nobs=nobs;
_obs_ = _n_;
end;
if _error_ eq 0 then
output;
stop;
set class(drop=_all_) end=eof;
run;
/* print last record */
proc print;
run;
Editor's note: this is a very popular question. To help others to find the answer, we have consolidated the most helpful answers into this one reply as an Accepted Solution.
or ...
/* Simple approach */
data last;
/* get number of records (N) */
if 0 then
set sashelp.class nobs=nobs end=eof;
/* use POINT= to get nth record */
set sashelp.class point=nobs;
output;
stop;
run;
More robust approach from @data_null__:
/* Create sample data */
data class;
set sashelp.class;
run;
data class;
modify class end=eof;
/* uncomment this to create empty set for test */
*remove;
if eof or ranuni(12344) lt .2 then
remove;
run;
/* print all records */
proc print;
run;
/* find last record, handle empty sets */
data last;
if eof then
stop;
do _n_ = nobs to 1 by -1 until(_error_ eq 0);
_error_ = 0;
set class point=_n_ nobs=nobs;
_obs_ = _n_;
end;
if _error_ eq 0 then
output;
stop;
set class(drop=_all_) end=eof;
run;
/* print last record */
proc print;
run;
Ever any new questions? Well I asked this one back in 2004...
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.