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

Here is my example dataset:

 

fruit apple  

fruit apple  

fruit orange

fruit orange 

fruit orange

vegetable celery

vegetable broccoli 

meat beef

meat chicken

 

How do I create a third column, that identifies the group number in column 1?

The resulting dataset should look like this

 

fruit apple  1

fruit apple  1

fruit orange 1

fruit orange 1

fruit orange 1

vegetable celery 2

vegetable broccoli 2

meat beef 3

meat chicken 3

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User
data want;
set have;
by col1 notsorted;
retain subgroup 0;
if first.col1 then subgroup + 1;
run;

You might consider sorting by col1 first, so you can omit the notsorted option and make sure that a certain subgroup does not receive more than one number.

View solution in original post

5 REPLIES 5
Kurt_Bremser
Super User
data want;
set have;
by col1 notsorted;
retain subgroup 0;
if first.col1 then subgroup + 1;
run;

You might consider sorting by col1 first, so you can omit the notsorted option and make sure that a certain subgroup does not receive more than one number.

schoi
Calcite | Level 5

Thanks!

 

I have other string columns in my RETAIN statement.  It doesn't seem to work if I put those columns in front of subgroup 0.  Anyway around this?

Kurt_Bremser
Super User

@schoi wrote:

Thanks!

 

I have other string columns in my RETAIN statement.  It doesn't seem to work if I put those columns in front of subgroup 0.  Anyway around this?


In order for in-depth help, post your code (with log if code fails with ERROR or WARNING) and some example data to test the code against. See @PeterClemmensen's example data step for how to post data.

PeterClemmensen
Tourmaline | Level 20
data have;
input food$ type$;
datalines;
fruit apple  
fruit apple  
fruit orange
fruit orange 
fruit orange
vegetable celery
vegetable broccoli 
meat beef
meat chicken
;

proc sort data=have;
	by food;
run;

data want;
	set have;
	by food;
	if first.food then groupnum+1;
run;
schoi
Calcite | Level 5

Thanks everyone!

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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