SAS如果全部保留,否则

时间:2018-11-29 19:45:35

标签: if-statement sas

我有一个如下的sas数据集:

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

,我想根据实例是否被标记为“ yes”来保留实例。否则它将标记为否。我想要的输出将是:

ID   Instance1  Instance2
1         Y         Y
2         N         Y

我正在尝试的伪代码:

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

3 个答案:

答案 0 :(得分:2)

使用RETAIN语句非常简单。在这里,它以相当冗长的方式清楚地显示了正在发生的事情。

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;

答案 1 :(得分:1)

这应该有效

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);

或通过数据步骤

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;

答案 2 :(得分:1)

您还可以使用滞后变量的另一种方法。这将与先前的值匹配,而最后的观察值将具有必需的变量。

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;