Solved
Contributor
Posts: 31

# 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

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: 6,781

## 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';

drop count;

run;

All Replies
Solution
‎05-12-2016 05:54 AM
Super User
Posts: 6,781

## 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';

drop count;

run;

Contributor
Posts: 31

## Re: Looking at previous observations

Thank you! Really appreciate it!
Super User
Posts: 10,784

## 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
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 and locked.