## How to select first and last row of a data

Solved
Super Contributor
Posts: 328

# How to select first and last row of a data

The first pick  the first row from the data set kaplan.

How come the statement _n_=n does not pick the last row.?

How do I pick the last row?

data KS_;

set Kaplan;

if _n_ =1 then keep=1;

if keep ne 1 then delete;

drop keep survival;

run;

data KSm_&p(rename=survival1=(survival_max time=time_max));

set Kaplan_&p;

if _n_ =n then keep=1;

if keep ne 1 then delete;

drop keep survival;

run;

Accepted Solutions
Solution
‎07-12-2013 10:25 AM
Regular Contributor
Posts: 171

## Re: How to select first and last row of a data

Hi desireatem,

You can try this to get last record

data KSm_&p(rename=survival1=(survival_max time=time_max));

set Kaplan_&p nobs=nobs;

if _n_ =nobs then keep=1;

if keep ne 1 then delete;

drop keep survival;

run;

Thanks

Sam

All Replies
Solution
‎07-12-2013 10:25 AM
Regular Contributor
Posts: 171

## Re: How to select first and last row of a data

Hi desireatem,

You can try this to get last record

data KSm_&p(rename=survival1=(survival_max time=time_max));

set Kaplan_&p nobs=nobs;

if _n_ =nobs then keep=1;

if keep ne 1 then delete;

drop keep survival;

run;

Thanks

Sam

Super Contributor
Posts: 1,636

## Re: How to select first and last row of a data

example:

data first_last;

set sashelp.class nobs=nobs;

if _n_ =1 or _n_=nobs;

proc print;run;

Obs     Name      Sex    Age    Height    Weight

1     Alfred      M      14     69.0      112.5
2     William     M      15     66.5      112.0

Message was edited by: Linlin

Super User
Posts: 6,785

## Re: How to select first and last row of a data

If your data set is large, you can skip reading the middle of it:

data want;

set have nobs=_nobs_;

output;

set have point=_nobs_;

output;

stop;

run;

Good luck.

Super User
Posts: 8,127

## Re: How to select first and last row of a data

Need to watch for when NOBS=1 .

data class ;

set sashelp.class (obs=1);

run;

data first_last ;

retain point 1 ;

set class point=point nobs=nobs ;

output;

if point = nobs then stop;

else point = nobs ;

run;

Contributor
Posts: 71

## Re: How to select first and last row of a data

Get the last row with the the END option in the SET statement.

data want; set sashelp.class end=eof;

if eof then output;

run;

EOF is short for end of file.  Programmers like to use this term, but you can put whatever you want here.  For example, this would also work:

data want2; set sashelp.class end=awesome;

if awesome then output;

run;

🔒 This topic is solved and locked.