DATA Step, Macro, Functions and more

Retain Flag Conditionally

Reply
Occasional Contributor
Posts: 10

Retain Flag Conditionally

Hi All,

 

I am trying to create a flag with the following rules at ID States Level. The Dataset has ID, States, Gap(Between consecutive states) and a condition flag.

 

Every time the for a given ID the Condition 1 = 1 (This is universally true)

 

The Flag as well inititates as Type1, then if for the next state for an ID the gap is >=180 then flag = Type2, else Type1 reatins to types 2. 

 

For states 3 and above, if the Condition 1 = 1 then reset to type and apply the above rule, else retain earlier flag.

 

Below is a sample datset...

 

ID	States	Gap	Condition 1	Flag
1087013	1	0	1	Type1
1087013	2	180	0	Type2
1087013	3	34	0	Type2
1087013	4	45	1	Type1
1087013	5	77	0	Type1
1103719	1	0	1	Type1
1103719	2	743	0	Type2
1103719	3	20	0	Type2
1103719	4	2	0	Type2
1103719	5	0	1	Type1
1103719	6	50	0	Type1
1103719	7	10	0	Type1
1103719	8	0	0	Type1
1126597	1	0	1	Type1
1126597	2	200	0	Type2
1126597	3	30	0	Type2
1126597	4	0	0	Type2
1293105	1	0	1	Type1
1297440	1	0	1	Type1

Any help is appreciated!!

 

Thanks in Advance

Super User
Posts: 19,770

Re: Retain Flag Conditionally

Posted in reply to SambitNandi

Retain flag;

 

if condition=1 then flag = 'Type1';

else if gap>=180 then flag = 'Type2';

 

This assumes you DO NOT have a variable named flag in your dataset already. 

Occasional Contributor
Posts: 10

Re: Retain Flag Conditionally

Posted in reply to SambitNandi
That is what I need to create.
Super User
Posts: 19,770

Re: Retain Flag Conditionally

Posted in reply to SambitNandi

SambitNandi wrote:
That is what I need to create.

Did the code not work? 

Super User
Posts: 5,497

Re: Retain Flag Conditionally

Posted in reply to SambitNandi

I think a little more needs to be built into the logic:

 

data want;

set have;

by ID;

if first.ID then flag='Type1';

else if gap >= 180 then flag='Type2';

if states >= 3 and condition_1=1 then flag='Type1';

retain flag;

run;

 

It's not 100% clear whether it is possible to have gap >= 180 for the first observation for a STATE.  What should happen in that case?

 

I can't test it today, so you'll need to try it to see if it gives you any trouble.

Ask a Question
Discussion stats
  • 4 replies
  • 312 views
  • 2 likes
  • 3 in conversation