Next is my final tested code.
I have added a test line for landing entry without exit.
Results fits your posted output.
data have;
length name $6 activity $20 screen $8 value $8;
infile cards;
input name $ activity $ screen $ valuex $ ;
value_time = 0; /* flag */
if strip(valuex) in ("1" "2")
then value = input(strip(valuex),1.);
else do;
value = input(valuex,hhmmss.);
value_time = 1;
end;
timestamp = _N_; /* dummy variable to save original order */
cards;
Mary Home_test_entry Home 2
Mary Home_test_exit Home 2
Mary Landing_test_entry Landing 1
Mary Landing_test_exit Landing 2
Mary Login_test_entry Login 1
Mary Login_test_entry Login 2
Mary Login_test_exit Login 1
Mary Login_test_exit Login 2
Mary Login_test_time Login 08:09:12
Mary Candy_test_entry Candy 2
Mary Candy_test_exit Candy 2
Tom Home_test_entry Home 2
Tom Home_test_exit Home 1
Mary Landing_test_entry Landing 2
Mary Landing_test_exit Landing 1
Xxxx Landing_test_entry Landing 1
;
run;
proc sort data=have; by name timestamp; run;
data temp;
set have;
by name;
length switch $15;
retain pre_activity pre_value;
pre_activity= lag(activity);
pre_value = lag(value);
pre_screen = lag(screen);
drop pre_activity pre_value pre_screen ;
if first.name then do;
pre_activity = "";
pre_value = "";
pre_screen = "";
end;
if screen = "Landing" then do;
if activity = "Landing_test_exit" then do;
if value ne pre_value then do;
if value=2
then switch = "One-Two";
else switch = "Two-One";
end;
/* else treat while value = pre_value ??? */
end;
end;
if screen ne "Landing" and
screen = pre_screen then do;
if value_time = 1
then switch = "Switch_time"; else
if value = pre_value
then switch = "No";
else switch = "Switch_within";
end;
run;
proc sort data=temp;
by name descending timestamp;
run;
data want;
set temp;
by name;
length pre_switch $15;
retain pre_activity pre_value;
pre_activity= lag(activity);
pre_value = lag(value);
pre_screen = lag(screen);
pre_switch = lag(switch);
drop pre_activity pre_value pre_screen pre_switch;
if first.name then do;
pre_activity = "";
pre_value = "";
pre_screen = "";
end;
if screen = "Landing" then do;
if activity = "Landing_test_entry" then do;
if value ne pre_value then do;
if value=1 then switch = "One-Two";
else switch = "Two-One";
end;
/* else treat while value = pre_value ??? */
end;
end;
if screen ne "Landing" and
/*screen ne pre_screen and*/
switch = " "
then switch = pre_switch;
run;
proc sort data=want; by name timestamp; run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
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.