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

I have a dataset that has multiple groups of observations. There is a variable, flag, which either takes value 1 or missing. I want to create a new variable to divide each group into subgroups based on the value of flag. Whenever flag = 1, start counting a new subgroup. Please see the code below as an example.

data have;
	input group flag;
	datalines;
101 .
101 .
101 1
101 .
101 1
101 .
101 .
102 .
102 1
102 .
102 .
;

data want;
	input group flag new_var;
	datalines;
101 . 1
101 . 1
101 1 2
101 . 2
101 1 3
101 . 3
101 . 3
102 . 1
102 1 2
102 . 2
102 . 2
;

1 ACCEPTED SOLUTION
3 REPLIES 3
Jagadishkatam
Amethyst | Level 16

please try the below code for flag2

 

data have;
	input group flag;
	datalines;
101 .
101 .
101 1
101 .
101 1
101 .
101 .
102 .
102 1
102 .
102 .
;

data want;
set have;
by group flag notsorted;
retain new_var;
if first.group then new_var=1;
else new_var+flag;
run;

 

 

Thanks,
Jag
andreas_lds
Jade | Level 19

If you want a more arcane solution, try:

data want;
	set have;
	by group;
	length new_var 8;
	retain new_var;
		
	new_var = ifn(first.group, 1, new_var) + sum(0, flag);
run;

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