BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
sascode
Quartz | Level 8
Hello,
I have a binary variable for each id like this:
ID Binary wanted(index)
1 0 0
1 0 0
1 1 0
1 0 1
1 0 2
1 0 3
2 0 0
2 1 0
2 0 1
3 1 0
3 0 1
......................
So assuming I have only first two variables,how I can generate third wanted(index)?
Note:Within each id, if binary before 1 is 0 then index is 0,then,when reaches 1,index starts from 0 and assigns index counts for each 0 after 1.
For instance, for ID 3 there are not 0 before 1 at binary, therefore it starts indexing directly.
Thanks.
1 ACCEPTED SOLUTION

Accepted Solutions
andreas_lds
Jade | Level 19

You need

  • a data step with "by Id"
  • "retain" to preserve the values of "index" and a helper-variable (increase)
  • reset index and increase when the a new id is read for the first time
Spoiler
data want;
	set have;
	by id;
	
	retain index increase;
	
	if first.id then do;
		index = 0;
		increase = 0;
	end;
	
	if binary then do;
		increase = 1;
	end;
	
	output;
	
	index = index + increase;
	
	drop increase;
run;

View solution in original post

2 REPLIES 2
andreas_lds
Jade | Level 19

You need

  • a data step with "by Id"
  • "retain" to preserve the values of "index" and a helper-variable (increase)
  • reset index and increase when the a new id is read for the first time
Spoiler
data want;
	set have;
	by id;
	
	retain index increase;
	
	if first.id then do;
		index = 0;
		increase = 0;
	end;
	
	if binary then do;
		increase = 1;
	end;
	
	output;
	
	index = index + increase;
	
	drop increase;
run;
sascode
Quartz | Level 8
I appreciate your help.
Thank you.

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 25. 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
  • 2 replies
  • 709 views
  • 1 like
  • 2 in conversation