SAS Data Integration Studio, DataFlux Data Management Studio, SAS/ACCESS, SAS Data Loader for Hadoop and others

How to keep first 2 obs conditioned upon 2 variables?

Accepted Solution Solved
Reply
Contributor
Posts: 23
Accepted Solution

How to keep first 2 obs conditioned upon 2 variables?

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.


Accepted Solutions
Solution
‎02-04-2016 01:06 PM
Super User
Posts: 9,687

Re: How to keep first 2 obs conditioned upon 2 variables?

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


All Replies
Solution
‎02-04-2016 01:06 PM
Super User
Posts: 9,687

Re: How to keep first 2 obs conditioned upon 2 variables?

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;
Contributor
Posts: 23

Re: How to keep first 2 obs conditioned upon 2 variables?

exactly what i needed, thank you!
Trusted Advisor
Posts: 1,131

Re: How to keep first 2 obs conditioned upon 2 variables?

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
Contributor
Posts: 23

Re: How to keep first 2 obs conditioned upon 2 variables?

this works too, thank you!
☑ This topic is solved.

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

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