【问题标题】:SAS - Working with consecutive months?SAS - 连续几个月工作?
【发布时间】:2014-08-01 18:10:46
【问题描述】:

根据下面的示例数据,我正在尝试识别至少连续 3 个月出现 STATUS_DATE 的帐户(按 ID 和 SEQ)。我已经搞砸了一段时间,我完全不知道如何解决它。

样本数据:

ID     SEQ   STATUS_DATE
11111    1   01/01/2014
11111    1   02/10/2014
11111    1   03/15/2014
11111    1   05/01/2014
11111    2   01/30/2014
22222    1   06/20/2014
22222    1   07/15/2014
22222    1   07/16/2014
22222    1   08/01/2014
22222    2   02/01/2014
22222    2   09/10/2014

我需要返回的东西:

ID      SEQ   STATUS_DATE
11111    1    01/01/2014
11111    1    02/10/2014
11111    1    03/15/2014
22222    1    06/20/2014
22222    1    07/15/2014
22222    1    07/16/2014
22222    1    08/01/2014

任何帮助将不胜感激。

【问题讨论】:

  • 为什么不发布您迄今为止尝试过的代码/方法?

标签: sas datastep


【解决方案1】:

这是一种方法:

data have;
input ID     SEQ   STATUS_DATE $12.;
datalines;
11111    1   01/01/2014
11111    1   02/10/2014
11111    1   03/15/2014
11111    1   05/01/2014
11111    2   01/30/2014
22222    1   06/20/2014
22222    1   07/15/2014
22222    1   07/16/2014
22222    1   08/01/2014
22222    2   02/01/2014
22222    2   09/10/2014
;
run;

data grouped (keep = id seq status_date group) groups (keep = group2);
    set have;
    sasdate = input(status_date, mmddyy12.);
    month = month(sasdate);
    year = year(sasdate);
    pdate = intnx('month', sasdate, -1);
    if lag(year) = year(sasdate) and lag(month) = month(sasdate) then group+0;
    else if lag(year) = year(pdate) and lag(month) = month(pdate) then count+1;
    else do;
        group+1;
        count = 0;
    end;
    if count = 0 and lag(count) > 1 then do;
        group2 = group-1;
        output groups;
    end;
    output grouped;
run;

data want (keep = id seq status_date);
    merge grouped groups (in=a rename=(group2=group));
    by group;
    if a;
run;

基本上,如果观察是连续几个月,我会给它们相同的组号,然后还创建一个数据集,其中包含超过 2 个观察的组的组数。然后我合并这两个数据集,只保留第二个数据集中的观察值,即超过 2 个观察值的观察值。

【讨论】:

  • 太棒了。这完美无缺。感谢您的帮助!
【解决方案2】:

跟随怎么样。但是,如果您想要的话,您可能希望在 Month 上排序

data want;
    do _n_ = 1 by 1 until(last.id);
    set survey;
    by id;
    if _n_ <=3 then output;
    end;
run;

【讨论】:

  • 这与问题有什么关系?它不会以任何方式识别连续个月。
  • 不幸的是,正如乔已经说过的那样,这并没有真正解决我想要做的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 2022-07-30
  • 2017-03-11
  • 2020-01-15
  • 2022-07-28
  • 1970-01-01
相关资源
最近更新 更多