Dear All:
My Data is as follows
ID Date VarA
1 01JAN2018 0
1 03JAN2018 0
1 21JAN2018 1
1 03FEB2018 1
1 20FEB2018 1
1 03MAR2018 0
1 15MAR2018 1
1 05APR2018 0
2 20JAN208 1
2 29JAN2018 0
2 05FEB2018 0
2 18FEB2018 1
2 22FEB2018 0
2 25FEB2018 0
I want to create a variable which tracks changes from 1 to 0 for VarA for each ID. So the data set I want is
ID Date VarA VarB
1 01JAN2018 0 0
1 03JAN2018 0 0
1 21JAN2018 1 0
1 03FEB2018 1 0
1 20FEB2018 1 0
1 03MAR2018 0 1
1 15MAR2018 1 0
1 05APR2018 0 2
2 20JAN208 1 0
2 29JAN2018 0 1
2 05FEB2018 0 1
2 18FEB2018 1 0
2 22FEB2018 0 2
2 25FEB2018 0 2
So the change occurs from 1 to 0 and I want to keep a track of the number of such changes.
Thanks so much.
Randy
data have;
input ID Date : $20. VarA ;
cards;
1 01JAN2018 0
1 03JAN2018 0
1 21JAN2018 1
1 03FEB2018 1
1 20FEB2018 1
1 03MAR2018 0
1 15MAR2018 1
1 05APR2018 0
2 20JAN208 1
2 29JAN2018 0
2 05FEB2018 0
2 18FEB2018 1
2 22FEB2018 0
2 25FEB2018 0
;
data want;
set have;
varb=0;
if id ne lag(id) then count=0;
if id eq lag(id) and vara=0 and lag(vara)=1 then count+1;
if vara=0 then varb=count;
drop count;
run;
The last value of varb is inconsistent, there is no change in vara for that observation.
Assuming the last value of varb in your example should be zero :
data want;
count = 0;
do until(last.id);
set have; by id vara notsorted;
if first.vara and vara = 0 then do;
count + 1;
varb = count;
end;
else varb = 0;
output;
end;
drop count;
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.