|
看看这样可不可以:
data test;
input id date : yymmdd10. dose freq;
format date yymmdd10.;
cards;
1 2006-9-30 25 1
1 2006-10-23 30 1
1 2006-10-24 30 1
2 2007-10-2 80 1
2 2007-10-4 90 1
2 2007-10-6 70 1
3 2008-3-1 50 1
3 2008-3-4 40 1
3 2008-3-8 45 1
4 2006-10-1 60 1
4 2006-10-2 35 1
4 2006-10-4 80 1
4 2007-1-1 70 1
4 2007-1-3 60 1
4 2007-1-4 50 1
;
data part1;
set test;
date1=lag(date);
dose1=lag(dose);
if id ne lag(id) then do;date1=.;dose1=.;end;
* stage;
retain stage 1;
if date1 ne . and date-date1>=7 then stage=stage+1;
if date1=. then stage=1;
* prepare for miss time;
if date1 ne . and 1<date-date1<7 then do;
time=1;
if date-date1>1 then act_time=date-date1-1;
else act_time=0;
end;
else do;
time=0;
act_time=0;
end;
* prepare for during;
retain dur_date;
if _n_=1 then dur_date=date;
if date1=. or stage ne lag(stage) then dur_date=date;
dur=date-dur_date+1;
if dur<=2 then during=1;
else if 2<dur<=10 then during=2;
else if dur>10 then during=3;
* prepare for drug adjust times and dosage;
retain adj_time 0;
if stage ne lag(stage) then dose1=.;
if dose1 ne . and stage = lag(stage) then adj_dose=dose-dose1;
else adj_dose=0;
if dose1=. then adj_time=0;
else if adj_dose ne 0 then adj_time=adj_time+1;
drop dur_date dur dose1 date1;
run;
proc sql;
create table part2 as
select id, stage,
/* Begin date and end date / theoretic drug days */
min(date) as st_date format=yymmdd10.,max(date) as end_date format=yymmdd10.,
max(date)-min(date)+1 as theo_days,
/* Miss time and actual miss time */
sum(time) as miss_time, sum(act_time) as act_miss_days
from part1
group by 1,2;
quit;
* Miss variable;
proc sql;
create table miss as
select distinct id,stage,1 as miss from part1
where id in
(select distinct id from part1 where act_time ne 0
group by id,stage having count(distinct act_time)=1);
quit;
proc sql;
create table part3 as
select a.*,ifn(miss=.,0,miss) as miss
from part2 a left join miss b
on a.id=b.id and a.stage=b.stage;
quit;
* Final datasets;
proc sql;
create table wanted as
select a.id,date,dose,freq,a.stage,b.st_date,b.end_date,b.miss_time,b.act_miss_days,
b.theo_days,b.miss,during,adj_time,adj_dose
from part1 a left join part3 b
on a.id=b.id and a.stage=b.stage
order by 1,2;
quit;
|