DATA Step, Macro, Functions and more

OBS Counts Within Group

Accepted Solution Solved
Reply
Contributor
Posts: 61
Accepted Solution

OBS Counts Within Group

Hi -- I'm in need of a way to flag observations in a dataset within a group by groups of 5. Is there an easy way to do this?

 

For example: 

 

GROUP OBS WANT
1 1 1
1 2 1
1 3 1
1 4 1
1 5 1
1 6 2
1 7 2
1 8 2
1 9 2
1 10 2
1 11 3
1 12 3
2 1 1
2 2 1
2 3 1
2 4 1
2 5 1
2 6 2
2 7 2
2 8 2
2 9 2
2 10 2

 

 


Accepted Solutions
Solution
‎05-25-2018 02:28 PM
PROC Star
Posts: 1,772

Re: OBS Counts Within Group

Posted in reply to mdavidson
data a;
do _n_=1 by 1 until(last.make);
set sashelp.cars;
by make;
if first.make then want=1;
if mod(_n_,5)=0 then do; output;want+1;end;
else output;
end;
keep  make model want;
run;

View solution in original post


All Replies
Super User
Posts: 23,683

Re: OBS Counts Within Group

Posted in reply to mdavidson
Try the MOD() function along with BY processing to reset COUNT at the start of each GROUP. .

IF mod(obs, 5) = 1 then count+1;
PROC Star
Posts: 1,772

Re: OBS Counts Within Group

Posted in reply to mdavidson

demo

data have;
input GROUP	OBS	;
cards;
1	1	1
1	2	1
1	3	1
1	4	1
1	5	1
1	6	2
1	7	2
1	8	2
1	9	2
1	10	2
1	11	3
1	12	3
2	1	1
2	2	1
2	3	1
2	4	1
2	5	1
2	6	2
2	7	2
2	8	2
2	9	2
2	10	2
;
data want;
set have;
by group;
if first.group then want=1;
if mod(obs,5)=0 then do; output;want+1;end;
else output;
run;
Contributor
Posts: 61

Re: OBS Counts Within Group

Posted in reply to novinosrin

I think that's close but not the expected result. For example, check the first 3 rows of the Audi group:

 

data a;
set sashelp.cars;
by make;
obs=_n_;
if first.make then want=1;
if mod(obs,5)=0 then do; output;want+1;end;
else output;
keep obs make model want;
run;

Solution
‎05-25-2018 02:28 PM
PROC Star
Posts: 1,772

Re: OBS Counts Within Group

Posted in reply to mdavidson
data a;
do _n_=1 by 1 until(last.make);
set sashelp.cars;
by make;
if first.make then want=1;
if mod(_n_,5)=0 then do; output;want+1;end;
else output;
end;
keep  make model want;
run;
Contributor
Posts: 61

Re: OBS Counts Within Group

Posted in reply to novinosrin
Thank you, this is perfect! Genius!
PROC Star
Posts: 1,772

Re: OBS Counts Within Group

Posted in reply to mdavidson

@mdavidson You are welcome. My apologies for the lack of attention to detail earlier.  I have had this problem for ages Smiley Sad . Have a good day

☑ This topic is solved.

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

Discussion stats
  • 6 replies
  • 160 views
  • 0 likes
  • 3 in conversation