Solved
Contributor
Posts: 61

# 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

``````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;``````

All Replies
Super User
Posts: 23,683

## Re: OBS Counts Within Group

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

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

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

``````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

Thank you, this is perfect! Genius!
PROC Star
Posts: 1,772