Pyrite | Level 9

## 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;

1 ACCEPTED SOLUTION

Accepted Solutions
Obsidian | Level 7

## 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

5 REPLIES 5
Obsidian | Level 7

## 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

Lapis Lazuli | Level 10

## 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

PROC Star

## 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

## 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;

Quartz | Level 8

## 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;

Discussion stats
• 5 replies
• 32820 views
• 8 likes
• 6 in conversation