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

Have

ID Order Age
1 2 71
1 2 71
1 3 77
1 3 77
2 4 30
2 4 30
2 7 37
2 7 37

Want

ID Order Age Visit
1 2 71 1
1 2 71 1
1 3 77 2
1 3 77 2
2 4 30 1
2 4 30 1
2 7 37 2
2 7 37 2

Code and output from my attempt

proc sort have; by id order; run;

data want;

set have;

by id order;

if first.id then visit = 1;

if last.id then visit = 2;

run;

ID Order Age Visit
1 2 71 1
1 2 71 .
1 3 77 .
1 3 77 2
2 4 30 1
2 4 30 .
2 7 37 .
2 7 37 2

Obviously this only does the very first and  last row, not sure how to fill in the others. Within each ID, the smaller order number should all be visit 1 and the larger should be visit 2. Order is random, but is always smaller for visit 1 and the same for both rows of a given visit.

1 ACCEPTED SOLUTION

Accepted Solutions
Reeza
Super User

Close 🙂

 

proc sort have; by id order; run;

data want;

set have;

by id order;

*set to 0 for first ID;
if first.id then visit = 0;
*for first order increment the visit variable (0 will go to 1 for first record);
if first.order then visit+1;
run;

View solution in original post

4 REPLIES 4
meriS
Fluorite | Level 6

Reply to point out a typo, the final 2 rows of order should be 7 in all tables.

Reeza
Super User

@meriS wrote:

Reply to point out a typo, the final 2 rows of order should be 7 in all tables.


Fixed that for you 🙂

Reeza
Super User

Close 🙂

 

proc sort have; by id order; run;

data want;

set have;

by id order;

*set to 0 for first ID;
if first.id then visit = 0;
*for first order increment the visit variable (0 will go to 1 for first record);
if first.order then visit+1;
run;
meriS
Fluorite | Level 6
Perfect, thank you!

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1462 views
  • 1 like
  • 2 in conversation