BookmarkSubscribeRSS Feed
adamhyman
Calcite | Level 5

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

4 REPLIES 4
adamhyman
Calcite | Level 5

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;

MikeZdeb
Rhodochrosite | Level 12

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

Ksharp
Super User

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

Haikuo
Onyx | Level 15

Can also use DOW's counter:

data want;

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

  set myfruit; by fruit;   output;

  end;

run;

Haikuo

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 4 replies
  • 949 views
  • 0 likes
  • 4 in conversation