【问题标题】:SAS Keep if all, elseSAS Keep if all, else
【发布时间】:2018-11-29 19:45:35
【问题描述】:

我有一个如下所示的 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

并且我想根据它们是否标记为是一次来保留实例。否则将被标记为否。我想要的输出是:

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; 

【问题讨论】:

    标签: if-statement sas


    【解决方案1】:

    使用 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;
    

    【讨论】:

    • 您的代码结果将为两个 ID 的两个实例生成“N”。如果该 ID 中甚至有一个 Y,我怎样才能让它产生一个 Y?
    • @SerenaLee 这正是它正在做的事情。保留语句保存 instance1Y 和 instance2Y 中的“Y”值。我刚刚运行它,它会产生你想要的输出。
    • 感谢您的回复。我可能遗漏了一些东西,但是当我在使用上述 Rhythm 的测试数据后运行代码时,我得到了所有的“N”。
    【解决方案2】:

    这应该可以工作

    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;
    

    【讨论】:

      【解决方案3】:

      您还可以使用使用滞后变量的替代方法。这将与之前的值匹配,并且最后的观察值将具有所需的变量。

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多