BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
jlajla
Obsidian | Level 7

Hello,  how would I keep the first two observations conditioned upon it being the first observation of 2 variables?

 

For example, I have:

 

ID  Year Month Time

1      95     1     1

1      95     1      2

1      95     1      3

1      95     2      1

1      95     2       2

1      95     2       3

1      95     2       4

1      96     3       1

1      96     3       2

1      96     3       3

 

And need:

ID  Year Month Time

1      95     1       1

1      95     1       2

1      95     2       1

1      95     2       2

 

1      96     3       1

1      96     3       2

 

I've found how this can be achieved conditional upon the first 2 observations of one variable:

data top2(drop=count);
  set groups;
  by group descending amount;
  if first.group then count=0;
  count+1;
  if count le 2 then output;
run;

But I can't seem to find out how to do it conditioned upon the first 2 observations of 2 variables.  I've tried adding a second first.var, but this doesn't seem to work.

 

I'm using SAS Studio. Thank you.

1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User

Your code looks good . just change a little thing.

 

data top2(drop=count);
  set groups;
  by ID  Year Month;
  if first.Month then count=0;
  count+1;
  if count le 2 then output;
run;

View solution in original post

4 REPLIES 4
Ksharp
Super User

Your code looks good . just change a little thing.

 

data top2(drop=count);
  set groups;
  by ID  Year Month;
  if first.Month then count=0;
  count+1;
  if count le 2 then output;
run;
jlajla
Obsidian | Level 7
exactly what i needed, thank you!
Jagadishkatam
Amethyst | Level 16

You may also try the proc sql method

proc sort data=have;
by id year month time;
run;

proc sql;
create table test(where=(s<=2)) as select *, (monotonic()-min(monotonic())+1) as s from have
group by id,year,month
order by id, year, month,time  ;
quit;
Thanks,
Jag
jlajla
Obsidian | Level 7
this works too, thank you!

SAS Innovate 2025: Call for Content

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 16. Read more here about why you should contribute and what is in it for you!

Submit your idea!

How to connect to databases in SAS Viya

Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 4 replies
  • 2133 views
  • 9 likes
  • 3 in conversation