DATA Step, Macro, Functions and more

Looking at previous observations

Accepted Solution Solved
Reply
Contributor
Posts: 31
Accepted Solution

Looking at previous observations

Hi all,

 

I'm trying to do the following but I'm not sure how to look at the previous observations.

My data:

Month   ID   Indicator

Jan        A        Y

Feb       A        N

Mar       A        Y

Apr        A        Y

May      A         Y

June     A        N

 

What I am trying to do is that, if there are 3 consecutive Y indicators in consecutive months for the same ID, then in that month, it will be a BAD. I have already sorted by ID (there will be other IDs in the same months as well), but cannot think of ways to use first. and last. in this case. 

My output will be:

Month   ID   Indicator  Quality

Jan        A        Y          Good

Feb       A        N          Good

Mar       A        Y          Good

Apr        A        Y          Good

May      A         Y          BAD

June     A        N          Good

 

Hope you guys will be able to guide me on how to do this. 

Thank you!


Accepted Solutions
Solution
‎05-12-2016 05:54 AM
Super User
Posts: 5,080

Re: Looking at previous observations

Here's a way:

 

data want;

set have;

by ID;

if first.ID then count=0;

if indicator='N' then count=0;

else count + 1;

if count < 3 quality='Good';

else quality='BAD';

drop count;

run;

 

View solution in original post


All Replies
Solution
‎05-12-2016 05:54 AM
Super User
Posts: 5,080

Re: Looking at previous observations

Here's a way:

 

data want;

set have;

by ID;

if first.ID then count=0;

if indicator='N' then count=0;

else count + 1;

if count < 3 quality='Good';

else quality='BAD';

drop count;

run;

 

Contributor
Posts: 31

Re: Looking at previous observations

Thank you! Really appreciate it! Smiley Very Happy
Super User
Posts: 9,671

Re: Looking at previous observations

Assuming there are not gap(missing month) in MONTH variable.

 

CODE NOT TESTED.

 

data want;

 set have;

 Quality='GOOD';

 if id=lag(id) and id=lag2(id) and

   Indicator ='Y' and lag(Indicator )='Y' and lag2(Indicator )='Y' then Quality='BAD';

run;

Contributor
Posts: 31

Re: Looking at previous observations

Will try it, thank you too!
Occasional Contributor BPD
Occasional Contributor
Posts: 12

Re: Looking at previous observations

Here's an easy way to read behind:

 

data samp_rd;
set samp nobs=nobs;
IF _N_ >= 2 then set samp(keep = indicator rename=(indicator=ind2));
IF _N_ >= 3 then Set samp (keep = indicator rename=(indicator=ind3));
put _all_;
run;

 

It reads and renames the variable you're interested in first when you get to your second obs and then when you get to your 3rd obs.

When indicator = ind2 = ind3 = 'Y' , you've found the condition you're looking for.

 

Regards,

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 237 views
  • 2 likes
  • 4 in conversation