根据先前的行更新基线值

Update Baseline Value Based on Previous Rows

每个主题都有一个基线。一旦该值与基线之间的差异超过 5,该值将成为所有未来比较的基线,直到另一个值超过该新基线 5。

这是我希望输出数据的样子:

这就是我得到的

这是我当前的代码,它使我与我尝试过的任何代码一样接近。我尝试了 retain、lag() 和 ifn (suggested in this post)

的不同组合
Data Have;
 Input Visit usubjid Baseline Value;
 datalines;
1 1 112.2 112.2
2 1 112.2 113.7
3 1 112.2 112
3 1 112.2 108
4 1 112.2 109
5 1 112.2 107
7 1 112.2 106
8 1 112.2 107
; 
run;

proc sort;by usubjid;run;

data want;
 Length chg ;
 retain chg;
 set Have;
 length prevchg ;
 by usubjid;
 prevchg=chg;
 if first.usubjid then do; prevchg=''; end;
 baseline=ifn(prevchg in ('Increase >= 5mm New', "Decrease >= 5mm"),lag(value),lag(baseline));

 diff = value-baseline;
 if visit > 1 then do;
  if diff > 5 then do; chg='Increase >= 5mm New'; order = 3; end;
  else if diff < -5 then do; chg = 'Decrease >= 5mm'; order = 6; end;
  else if -5 <= diff <= 5 then do; 
    if prevchg in('Increase >= 5mm New', 'Increase > 5mm Persistent') then do; chg ='Increase > 5mm Persistent'; order = 4; end;
    else do; chg = 'No Change (change >= -5 and <= 5mm)'; order = 5; end;
  end;
 end;
run;

现在代码会正确地将基线更新为下一次访问的先前值,但随后又会立即返回到原始基线。我相信这与 Lag() 和 Retain 与 if/then 的工作方式有关,但我无法找出解决方案。这是问题的示例:

您应该能够轻松做到这一点。如果您想保留其值,则 BASELINE 变量不能在输入中。

data want ;
  set have ;
  by usubjid;
  retain baseline;
  if first.usubjid then baseline=value;
  difference = baseline - value;
  output;
  if difference > 5 then baseline=value;
run;