【问题标题】:Calculate a date difference within a group variable, over rows of missing observations计算组变量内的日期差异,在缺失观察的行上
【发布时间】:2015-02-17 20:59:08
【问题描述】:

在 SAS 中,我的 ID、Date1 和 Date2 按 ID、Date1 和 Date2 升序排序。根据需要,排序会导致缺少的 Date2 值位于它们所在的位置。如何计算具有有效日期的行之间的 Date2 差异并获得 D_Date2 中显示的结果?

字面意思是:BY ID,跳过 Date2 中缺失的日期值,读取其下的下一个有效日期,从较晚的日期中减去较早的日期,并将差值作为 D_Date2 写入具有有效 Date2 值的行.谢谢。

Obs ID  Date1      Date2        D_Date2
1   1   20090815   20090818       .
2   1   20090815   20090818       0
3   1   20090816   20090820       2
4   1   20090816          .       .
5   1   20090816   20090820       0
6   2   20090101          .       .
7   2   20090105   20090105       .
8   2   20090105          .       .
9   2   20090105   20090106       1
10  2   20090105   20090110       4
11  3   20080720          .       .
12  3   20080720   20080917       .
13  3   20080720   20080918       1
14  3   20081010          .       .
15  3   20081010   20080925       7
16  3   20081010   20080925       0

【问题讨论】:

  • 感谢您的纠正!

标签: sas retain


【解决方案1】:

我确定你可以使用retain,但我会使用lag 函数。这里的关键是要了解lag 函数确实不一定返回前一行的值。如果它遵循if 条件,则lag 函数将返回条件为真的最后一行的值。

为了清晰起见,我喜欢一步一步地做这些事情。首先,我创建一个新变量 ldate2,其中包含要减去的日期以获得所需的差异,然后执行减法。

data want;
  set have;
  if not missing(date2) then do;
    ldate2 = lag(date2);
    if id ne lag(id) then ldate2 = .;
  end;
  d_date2 = date2 - ldate2;
run;

正如 rbet 建议的那样,使用 dif 函数更简单。 dif 的行为类似于 lag,只是它从当前值中减去前一个值,因此无需单独执行减法:

data want;
  set have;
  if not missing(date2) then do;
    d_date2 = dif(date2);
    if id ne lag(id) then d_date2 = .;
  end;
run;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    相关资源
    最近更新 更多