Wayne
Wayne

Reputation: 33

Use if first statement in a single variable is SAS

Hello: I have a question. I have a sas dataset like this:

data a;
input id $ a b ;
cards;
ddd 12  1
ddd 22  1
ddd 44  2
ddd 50  1
ddd 52  1
ddd 88  2
;run;

and I expect I can use if first to flag the obs lake this:

data a;
input id $ a b flag $;
cards;
ddd 12  1  Y
ddd 22  1  
ddd 44  2  Y
ddd 50  1  Y
ddd 52  1  
ddd 88  2  Y
;run;

In order to do that, I sort the dataset by ID, a,b and tried to use if first.b to create flag. But it flags all the obs with Y. I think it might be the reason that I sort by a before b. But in order to keep the dataset in this order, I have to sort it by a,b. So, my question is how can I keep the order and use first.b to create the flag? Thanks.

Upvotes: 0

Views: 91

Answers (2)

Tom
Tom

Reputation: 51566

You just need to use the NOTSORTED option on the BY statement so that SAS will set the FIRST. and LAST. flags as want them.

data want ;
  set a ;
  by id b notsorted;
  flag = first.b ;
run;

enter image description here

Upvotes: 1

david25272
david25272

Reputation: 974

I'm assuming you're using set by a b; in combination with first.b. The reason first.b doesn't work in this case is because first.b will be true for the first value of b inside an a group, and in this case there is only one b within each a.

This alternative should work, it retains the previous value of b and checks it each time.

data flagged (drop=prev_b);
 set a;
 retain prev_b;
 if b ne prev_b then flag='Y';
 output;
 prev_b=b;
run;

Upvotes: 1

Related Questions