Hello all,
I have a dataset that looks like this:;
ID | Month | Right | Left |
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 |
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):
ID | Month | Right | Left | right flag | leftflag |
1 | 1 | 10 | 5 | 1 | . |
1 | 2 | 11 | 6 | 1 | . |
1 | 3 | 8 | 10 | 1 | . |
2 | 1 | 7 | 10 | . | 1 |
2 | 2 | 8 | 10 | . | 1 |
2 | 3 | 8 | 11 | . | 1 |
3 | 1 | 7 | 7 | 1 | . |
3 | 1 | 10 | 7 | 1 | . |
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;
ID | Month | Right | Left | right flag | leftflag |
1 | 1 | 10 | 5 | 1 | . |
1 | 2 | 11 | 6 | . | . |
1 | 3 | 8 | 10 | . | . |
2 | 1 | 7 | 10 | . | 1 |
2 | 2 | 8 | 10 | . | . |
2 | 3 | 8 | 11 | . | . |
3 | 1 | 7 | 7 | . | . |
3 | 1 | 10 | 7 | . | . |
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!
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;
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;
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.
Ready to level-up your skills? Choose your own adventure.