Try this
data have;
input Student $ Device $;
datalines;
A Mac
A Tablet
A Laptop
B PC
B ANDROID
B ANDROID
C TABLET
C TABLET
C IPHONE
;
data want(drop = d);
do until (last.Student);
set have;
by Student;
d = lag(Device);
flag = (last.Student and Device ne d);
end;
do until (last.Student);
set have;
by Student;
output;
end;
run;
Result:
Student Device flag A Mac 1 A Tablet 1 A Laptop 1 B PC 0 B ANDROID 0 B ANDROID 0 C TABLET 1 C TABLET 1 C IPHONE 1
Try this
data have;
input Student $ Device $;
datalines;
A Mac
A Tablet
A Laptop
B PC
B ANDROID
B ANDROID
C TABLET
C TABLET
C IPHONE
;
data want(drop = d);
do until (last.Student);
set have;
by Student;
d = lag(Device);
flag = (last.Student and Device ne d);
end;
do until (last.Student);
set have;
by Student;
output;
end;
run;
Result:
Student Device flag A Mac 1 A Tablet 1 A Laptop 1 B PC 0 B ANDROID 0 B ANDROID 0 C TABLET 1 C TABLET 1 C IPHONE 1
data want;
set have;
by student; /* add notsorted option if necessary */
ldev = lag(device); /* keep previous value of device */
if
last.student /* test only at last observation of student */
and device ne ldev /* compare devices */
and not first.student /* students with only one entry are never flagged */
then flag = 1;
else flag = 0;
drop ldev;
run;
That would flag all students who have only one entry. The condition should be
if last.student ne first.student and first.device then flag=1;
Good catch, @Kurt_Bremser . I could have been more careful. However, the suggestion you made won't do the job. It will flag the first observation for each student (as long as the student has more than one observation).
Here is a more careful variation:
data want;
set have;
by student device notsorted;
if last.student and first.device and not first.student then flag=1;
run;
You're right. Yours is the first solution I also came up with, but then I obviously wanted to be overly cute 😉
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.