DATA Step, Macro, Functions and more

Select observations within group

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 5
Accepted Solution

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;

View solution in original post


All Replies
Super User
Posts: 19,869

Re: Select observations within group

Posted in reply to MichaelGong
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.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 167 views
  • 3 likes
  • 3 in conversation