STL
STL

Reputation: 293

SAS Keep if all, else

I have a sas dataset that looks like the following:

ID    Day    Instance1  Instance2
1      1         N         Y
1      2         N         Y
1      3         Y         N
1      4         N         N
2      1         N         Y
2      2         N         N
2      3         N         Y  
2      4         N         N

and I would like to keep instances based on whether or not they are marked yes even once. Else it would be marked no. My desired output would be:

ID   Instance1  Instance2
1         Y         Y
2         N         Y

What I'm trying pseudo code:

DATA test, 
    set.test, 
    by ID;
       if all instance1 = N then N, else yes; 
       if all instance2 = N then N, else yes;
RUN; 

Upvotes: 1

Views: 312

Answers (3)

Craig Srsen
Craig Srsen

Reputation: 475

That's fairly simple using a RETAIN statement. Here it is in a fairly verbose manner to clearly show what's going on.

DATA test;
set test;
by ID;
retain instance1Y instance2Y;

if first.ID then do;
  instance1Y=instance1;
  instance2Y=instance2;
end;

if instance1='Y' then instance1Y='Y';
if instance2='Y' then instance2Y='Y';

if last.ID then do;
  instance1=instance1Y;
  instance2=instance2Y;
  output;
end;
run;

Upvotes: 2

Kiran
Kiran

Reputation: 3315

this should work

proc sql;
select distinct id,  max(instance1) as instance1_max ,
max(instance2) as instance2_max
from have
group id
having instance1 =max(instance1)
or instance2 = max(instance2);

or by datastep

proc sort data=have out=have1;
by id;
run;

data want(rename = (instance1_final = instance1 instance2_final = instance2));
do until(last.id);
set have1;
by id;
if instance1 ='Y' then instance1_final ='Y';
if instance1_final = ' ' then instance1_final='N';
if instance2 ='Y' then  instance2_final ='Y';
if instance2_final = ' ' then instance2_final='N';
end;
drop instance1 instance2 Day;
if instance1_final = "Y" or  instance2_final = "Y";
run;

Upvotes: 1

Rhythm
Rhythm

Reputation: 682

You can also use an alternative approach of using lag variables. This will match with the previous value and the last observation will have the required variables.

data test;
input Id 1. I1 $1. I2 $1.;
datalines;
1NY
1NY
1YN
1NN
2NY
2NN
2NY  
2NN
;
run;

proc sort data=test; by Id I1 I2; run;

data test1;
 set test;
  by Id I1 I2;
  if I1='Y' or lag(I1)='Y' then Ins1='Y';
  else Ins1='N';
  if I2='Y' or lag(I2)='Y' then Ins2='Y';
  else Ins2='N';
  if last.Id;
  drop I1 I2;
run;

proc print data=test1; run;

Upvotes: 1

Related Questions