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

I want to add a group number to the first dataset (see the second one). Does anyone know how?

I cannot use sort because some categories have the same name. I can only determine the group by the existing data order.

Thanks!

dataset 1:

a

a

b

b

b

c

c

d

d

d

b

b

dataset 2:

a 1

a 1

b 2

b 2

b 2

c 3

c 3

d 4

d 4

d 4

b 5

b 5

1 ACCEPTED SOLUTION

Accepted Solutions
Reeza
Super User

Use the NOTSORTED option of by groups with a retain statement:

data want;

set have;

by id notsorted;

retain group 0;

if first.id then group=group+1;

run;

View solution in original post

5 REPLIES 5
Peter_C
Rhodochrosite | Level 12

set statement referring to a single dataset allows the by statement to use the NOTSORTED option

Peter_C
Rhodochrosite | Level 12

A simple version would be

data ds2 ;

set ds1 ;

by id notsorted ;

group_no + first.id ;

run ;

ballardw
Super User

If the two datasets have the exact same number of records then this may work:

data new;

     set dataset1;

     set dataset2;

run;

Reeza
Super User

Use the NOTSORTED option of by groups with a retain statement:

data want;

set have;

by id notsorted;

retain group 0;

if first.id then group=group+1;

run;

Ken_oy
Fluorite | Level 6

I make my own version too, thank you all for the ideas!

data want;

set test;

retain group 0;

if lag( id ) ne  id then group +1;

run;

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
  • 5 replies
  • 1072 views
  • 9 likes
  • 4 in conversation