简体   繁体   English

使用 SAS 按组计算日期之间的持续时间

[英]Calculate duration between dates by group using SAS

I am trying to calculate how long a child has been in foster care.我试图计算一个孩子在寄养中的时间。 However, I am having some issues.但是,我遇到了一些问题。 My data should look like something below:我的数据应如下所示:

在此处输入图像描述

For each individual (ID) I need to calculate the duration (end_date-start_date).对于每个人(ID),我需要计算持续时间(end_date-start_date)。 However, I also need to apply a rule that states that if there are less than 5 days between the end date and the start date within the same type of foster care, it should be considered as one consecutively placement.但是,我还需要应用一条规则,即如果在同一类型的寄养中,结束日期和开始日期之间的时间少于 5 天,则应视为连续安置。 If there are more than five days between the end date end the start date within the same type of foster care for the same individual, it is a new placement.如果同一个人在同一类型的寄养中的结束日期和开始日期之间有超过五天的时间,则这是一个新的安置。 If it is a new type of foster care, it is a new placement.如果是新型寄养,那就是新安置。 The variable “duration” is how, it is supposed to be calculated.变量“持续时间”是应该如何计算的。

I have tried the following code, but it doesn't work the proper way + I don't know how to apply my "five day"-rule.我尝试了以下代码,但它不能以正确的方式工作 + 我不知道如何应用我的“五天”规则。

Proc sort data=have out=want;
by id type descending start_date;
run;

Data want;
set want;
by id type;
retain last_date;
if first.id or first.type then do;
   last_date=end_date;
end;  
if last.id or last.type then duration=(end_date-start_date);
run;

Any help is much appreciated!任何帮助深表感谢!

Using a bunch of retain statements here to achieve this:在这里使用一堆保留语句来实现这一点:

data want;
  set have;

  by id ;

  retain true_sd prev_ed prev_type;

  if first.id then call missing(prev_type);

  if type ~= prev_type then do;
     true_sd = sd;
     call missing(prev_ed);
     call missing(prev_type);
  end;

  if sd - prev_ed > 5 then true_sd = sd;

  duration = ed - true_sd;
  output;

  prev_type = type;
  prev_ed = ed;

  format sd ed true_sd prev_ed date.;


 run;

(assuming type and id are numeric here. ed is end_date, sd is start_date) (假设 type 和 id 在这里是数字。ed 是 end_date,sd 是 start_date)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM