BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
angel2
Calcite | Level 5

How can I use a data step to create a count unique by ID and category. I want the same count to remain for non unique values. Please see example attached and the wanted counts. Thanks

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

data have;
input (ID	CATEGORY) ($);*		WANTED COUNT;
cards;
001	PIG		1
001	PIG		1
003	SHEEP		1
003	PIG		2
003	PIG		2
004	SHEEP		1
004	SHEEP		1
005	PIG		1
005	PIG		1
005	COW		2
005	SHEEP		3
;

data want;
 set have;
 by id category notsorted;
 if first.id then count=1;
 else if first.category then count+1;
run;

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20

data have;
input (ID	CATEGORY) ($);*		WANTED COUNT;
cards;
001	PIG		1
001	PIG		1
003	SHEEP		1
003	PIG		2
003	PIG		2
004	SHEEP		1
004	SHEEP		1
005	PIG		1
005	PIG		1
005	COW		2
005	SHEEP		3
;

data want;
 set have;
 by id category notsorted;
 if first.id then count=1;
 else if first.category then count+1;
run;
RichardDeVen
Barite | Level 11

Presuming the data is grouped into contiguous blocks the syntax BY var1 var2 NOTSORTED; can be used.  This assumption is made because group 5 is not sorted in alphabetical order.

 

data have; input
ID  CATEGORY $  wanted; datalines;
001  PIG        1
001  PIG        1
003  SHEEP      1
003  PIG        2
003  PIG        2
004  SHEEP      1
004  SHEEP      1
005  PIG        1
005  PIG        1
005  COW        2
005  SHEEP      3
;

data want;
  set have;
  by id category notsorted;
  if first.id then seq=0;
  if first.category then seq+1;
run;

 

Output

RichardADeVenezia_0-1606322652894.png

 

angel2
Calcite | Level 5

Thank you so much - that's perfect!

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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
  • 3 replies
  • 941 views
  • 5 likes
  • 3 in conversation