BookmarkSubscribeRSS Feed
meriS
Fluorite | Level 6

Hello all, 

I have a dataset that looks like this:;

IDMonthRightLeft
11105
12116
13810
21710
22810
23811
3177
31107

I'd like to add a flag for each user showing whether right or left is higher. If right and left start as equal, I'd like it to check at the second month and check which is higher there. So, I'd like the result to look like this (note that the flag stays the same even if right/left switch later on, see ID 1, Month 3):

IDMonthRightLeftright flagleftflag
111051.
121161.
138101.
21710.1
22810.1
23811.1
31771.
311071.

So far, I can get the flags to show up for the first month, looking like this: 

data result;
set result;
if month = 1 and (right > left) then rightflag = 1;
if month = 1 and (left > right) then leftflag = 1;
run;

IDMonthRightLeftright flagleftflag 
111051.
12116..
13810..
21710.1
22810..
23811..
3177..
31107..

 

I'd like to know how I can get that flag to fill in for all rows having the same ID, and how to implement the "move to second month" check if right = left at month 1. Thank you!

2 REPLIES 2
Ksharp
Super User
data have;
infile cards expandtabs truncover;
input ID	Month	Right	Left;
cards;
1	1	10	5
1	2	11	6
1	3	8	10
2	1	7	10
2	2	8	10
2	3	8	11
3	1	7	7
3	1	10	7
;

data temp;
 set have;
if (right > left) then _rightflag = 1;
if (left > right) then _leftflag = 1;
run;

data want;
 do until(last.id);
   set temp;
   by id;
   if not missing(_rightflag) and not found then do;found=1;rightflag=_rightflag;end;
   if not missing(_leftflag) and not found then do;found=1;leftflag=_leftflag;end;
 end;
 do until(last.id);
   set temp;
   by id;
   output;
 end;
drop _rightflag _leftflag found;
run;
andreas_lds
Jade | Level 19

Is it correct that both obs with id=3 have month=1?

This seems to work, too:

data want;
   if 0 then set have;
   length r_flag l_flag 8;
   
   do _n_ = 1 by 1 until (last.id);
      set have;
      by id;
   
      if first.id or (sum(l_flag, r_flag) = 0) then do;
         r_flag = Right > Left;
         l_flag = Left > Right;
      end;  
   end;
      
   do _n_ = 1 by 1 until (last.id);
      set have;
      by id;
      output;
   end;
run;

 

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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
  • 1597 views
  • 0 likes
  • 3 in conversation