Select observations within group

Solved
Occasional Contributor
Posts: 5

Select observations within group

Hi all,

I met a problem which really bothers me a lot.

here is my data set:

ID    Date    Shares

1     1991     70

1     1991     65

1     1991     62

1     1992     80

1     1992     79

1     1992     69

2     1991     55

2     1991     52

2     1991     44

2     1992     85

3     1991     78

3     1991     76

3     1992     59

I want to extract the TOP 2 observations WITHIN in each ID&Date group, so below is my desired data set

ID     Date     Shares

1     1991     70

1     1991     65

1     1992     80

1     1992     79

2     1991     55

2     1991     52

2     1992     85

3     1991     78

3     1991     76

3     1992     59

I was thinking to give each observation within each ID&Date group a number starting from 1 to number of observation of this subgroup, then I can delete the observation with number larger than 2.

But unfortunately I failed...Does anyone can help me to figure out how to do that? I really appreciate!!!

Accepted Solutions
Solution
‎05-27-2013 08:34 AM
Occasional Contributor
Posts: 10

Re: Select observations within group

use full code

proc sort data=dsn;

by id date;

run;

data dsn22;

set dsn;

by id date;

if first.date then cnt=1;

else cnt+1;

if cnt <=2;

drop cnt;

run;

All Replies
Super User
Posts: 23,771

Re: Select observations within group

Solution
‎05-27-2013 08:34 AM
Occasional Contributor
Posts: 10

Re: Select observations within group

use full code

proc sort data=dsn;

by id date;

run;

data dsn22;

set dsn;

by id date;

if first.date then cnt=1;

else cnt+1;

if cnt <=2;

drop cnt;

run;

🔒 This topic is solved and locked.