DATA Step, Macro, Functions and more

Numbering of Groups

Reply
Occasional Contributor
Posts: 9

Numbering of Groups

If I have a sorted table like this:

DATA myfruit;

   INPUT fruit $40.;

   DATALINES;

APPLE
APPLE

APPLE
PEACH
PEACH

;

RUN;

I would like to add the "Count" column like this:

FruitCount
APPLE1
APPLE2
APPLE3
PEACH1
PEACH2

I know that I have to do something like this, I can't get it quite right.

data myfruit;

set myfruit;

     by fruit;

          Count = _N_;

run;

Any help would be greatly appreciated.

Thanks!
Adam

Occasional Contributor
Posts: 9

Re: Numbering of Groups

Posted in reply to adamhyman

I worked it out, so am posting the solution.

data myfruit;

set myfruit;

     by fruit;

     retain count;

     if first.fruit then count = 1;

     else count + 1;

run;

Valued Guide
Posts: 765

Re: Numbering of Groups

Posted in reply to adamhyman

hi ...

data myfruit;

set myfruit;

by fruit;

count + (-first.fruit * count) + 1;

run;

ps ... http://www.sascommunity.org/wiki/Tips:Between_and_Within_Group_Counters

Super User
Posts: 10,046

Re: Numbering of Groups

Posted in reply to adamhyman

Assuming your dataset has already sorted before.

DATA myfruit;
   INPUT fruit $40.;
   DATALINES;
APPLE
APPLE
APPLE
PEACH
PEACH
;
RUN;

data myfruit;
set myfruit;
if fruit ne lag(fruit) then count=0;
Count+1;
run;

Ksharp

Respected Advisor
Posts: 3,156

Re: Numbering of Groups

Posted in reply to adamhyman

Can also use DOW's counter:

data want;

  do count=1 by 1 until (last.fruit);

  set myfruit; by fruit;   output;

  end;

run;

Haikuo

Ask a Question
Discussion stats
  • 4 replies
  • 228 views
  • 0 likes
  • 4 in conversation