Hi
Lets say in this dataset I have repeated measures for one subject. However, I want to flag if the next observation is different from the previous one...for example the dataset looks like this
Subject Event
1 A
1 B
1 A
1 A
1 C
1 A
1 B
1 B
1 C
Now I want to flag if the next event is different from the prior one and my output should mark these values as a flag
Subject Event Flag
1 A Y
1 B Y
1 A Y
1 A
1 C Y
1 A Y
1 B Y
1 B
1 C Y
Is there a way to do this?
Looking at the wanted result, it seems that what you want to do is set flag to 'Y' when the previous event is different from the current?
data have;
input Subject Event $;
datalines;
1 A
1 B
1 A
1 A
1 C
1 A
1 B
1 B
1 C
;
data want;
set have;
if event ne lag1(event) then flag='Y';
run;
Result:
Subject Event flag 1 A Y 1 B Y 1 A Y 1 A 1 C Y 1 A Y 1 B Y 1 B 1 C Y
Looking at the wanted result, it seems that what you want to do is set flag to 'Y' when the previous event is different from the current?
data have;
input Subject Event $;
datalines;
1 A
1 B
1 A
1 A
1 C
1 A
1 B
1 B
1 C
;
data want;
set have;
if event ne lag1(event) then flag='Y';
run;
Result:
Subject Event flag 1 A Y 1 B Y 1 A Y 1 A 1 C Y 1 A Y 1 B Y 1 B 1 C Y
Hi,
You can use the LAG Function. If you want the value from the previous record, use LAG(variable).
If previous of previous record, use LAG2
.
.
.
Here's sample code
DATA sample;
INPUT Subject Event ;
DATALINES ;
1 1
1 2
1 3
1 4
1 5
1 5
1 6
;
RUN ;
DATA sample2 (Drop=Newx);
SET sample ;
newx = LAG(EVENT) ;
IF Event = newx THEN Flag = 'Y' ; ELSE Flag = 'N' ;
RUN ;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.