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