SAS / PROC SQL - 只要有重复(不只是删除重复),删除BY组中的所有观察

问题描述 投票:0回答:1

我是SAS的新手,如果他们满足两个条件,我正试图删除组。我目前有这个数据集:

ID ID_2 ID_3;

A 1 1;

A 1 1;

A 1 1;

A 2 0;

A 2 1;

B 3 0;

B 3 0;

我是由ID分组,然后是ID_2

我希望删除分组中的所有条目,只要(1)所有三个变量都存在重复 - 我不只是想删除重复项,我想删除整个组和(2)此重复涉及ID_3中的值“1”跨越每个组中的所有行。

换句话说,我想要的结果是:

ID ID_2 ID_3;

A 2 0;

A 2 1;

B 3 0;

B 3 0;

我已经花了至少5个小时,我尝试了各种方法:

  • 第一。最后。 (这并不能保证按组匹配的所有观察结果)
  • nodup(此方法仅删除重复项 - 我想删除该组的第一行)
  • 滞后(再次,该组的第一行停留不是我想要的)

我也愿意使用proc sql。真的很感激任何输入,谢谢你提前!

sql sas
1个回答
0
投票

我相信这会实现你想要的。我猜,逻辑可以调整得更清晰一点,但是当我测试它时它就有用了。

data x;
    input id $ id_2 id_3;
cards;
A 1 1
A 1 1
A 1 1
A 2 0
A 2 1
B 3 0
B 3 0
;
run;

* I realize the data are already sorted, but I think it is better
* not to assume they are.;
proc sort data=x;
    by id id_2 id_3;
run;

* It is helpful to create a dataset for the duplicates as well as the 
* unduplicated observations.;
data nodups
     dups
     ;

    set x;
    by id id_2 id_3;

    * When FIRST.ID_3 and LAST.ID_3 at the same time, there is only
    * one obs in the group, so keep it;
    if first.id_3 and last.id_3
     then output nodups;

     * Otherwise, we know we have more than one obs. According to
     * the OP, we keep them, too, unless ID_3 = 1;
     else do;
        if id_3 = 1
         then output dups;
         else output nodups;
     end;

run;
© www.soinside.com 2019 - 2024. All rights reserved.