【问题标题】:SAS/PROC SQL - remove ALL observations in BY group as long as there are duplications (not just remove the duplications)SAS/PROC SQL - 只要有重复就删除 BY 组中的所有观察结果(不仅仅是删除重复)
【发布时间】:2016-11-11 05:45:33
【问题描述】:

我是 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 分组。

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

也就是说,我想要的结果是:

ID ID_2 ID_3;

A 2 0;

A 2 1;

B 3 0;

B 3 0;

我已经为此花费了至少 5 个小时,并且尝试了各种方法:

  • 首先。最后。 (这并不能保证按组中的所有观察结果都匹配)

  • nodup(此方法只删除重复项 - 我什至想删除组的第一行)

  • 滞后(同样,该组的第一行保持不变,这不是我想要的)

我也愿意使用 proc sql。 非常感谢您的任何意见,在此先感谢您!

【问题讨论】:

  • 你尝试了什么?
  • 上述三种方法我都试过了。
  • 请发布您尝试过的代码并格式化您的数据 - 理想情况下是一个数据步骤,但至少删除空格和分号,以便轻松读入 SAS。 DoW 循环或 SQL 步骤可能会起作用。您可能也可以先/最后一个工作,但您需要同时检查 ID 和 ID3。

标签: sql sas


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-03
    • 2022-11-23
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    相关资源
    最近更新 更多