使用 SAS 在同一列内进行条件减法

Conditional Subtraction within the same column using SAS

这是我命名为“抗体”的数据集的一部分:

Row          Subject        Type               Procedure           Measurement              Output
1               500         Intial              Invasive             20                        20
2               500          Initial            Surface              35                        35
3               500          Followup          Invasive             54                        54-20
4               428          Followup          Outer                 29                        29-10
5               765          Seventh           Other                 13                       13-19
6                500          Followup          Surface              98                       98-35
7                428          Initial             Outer            10                        10                
8                765          Initial              Other            19                        19     
9                610          Third              Invasive            66                       66-17
10               610          Initial             Invasive            17                       17

我试图使用 proc sql 来执行此操作。目标是根据 "SUBJECT"、"TYPE" 和“PROCEDURE”列减去 "MEASUREMENT" 列中的数字。如果“SUBJECT”列中的两个值匹配且“PROCEDURE”列中的两个值匹配,则应从另一个测量中减去初始测量。例如,第 1 行 (20) 中的初始测量值应从第 3 行 (54) 中的后续测量值中减去,因为受试者 (500) 和程序(侵入性)匹配。此外,应从第 5 (13) 行的第七次测量中减去第 8 (19) 行中的初始测量,因为受试者 (765) 和程序(其他)匹配。结果应形成 "OUTPUT" 列。

提前致谢!

这里是一个散列对象的方法

data have;
input Subject Type $ 5-12 Procedure $ 15-22 Measurement;
datalines;
500 Initial   Invasive  20 
500 Initial   Surface   35 
500 Followup  Invasive  54 
428 Followup  Outer     29 
765 Seventh   Other     13 
500 Followup  Surface   98 
428 Initial   Outer     10 
765 Initial   Other     19 
610 Third     Invasive  66 
610 Initial   Invasive  17 
;

data want (drop=rc _Measurement);
   if _N_ = 1 then do;
      declare hash h (dataset : "have (rename=(Measurement=_Measurement) where=(Type='Initial'))");
      h.definekey ('Subject');
      h.definedata ('_Measurement');
      h.definedone();
   end;

   set have;
   _Measurement=.;

   if Type ne 'Initial' then rc = h.find();
   Measurement = sum (Measurement, -_Measurement);
run;

编辑:

data want (drop=rc _Measurement);
   if _N_ = 1 then do;
      declare hash h (dataset : "have (rename=(Measurement=_Measurement) where=(Type='Initial'))");
      h.definekey ('Subject');
      h.definedata ('_Measurement');
      h.definedone();
   end;

   set have;
   _Measurement=.;

   if Type ne 'Initial' then rc = h.find();
   NewMeasurement = ifn(Measurement=., ., sum (Measurement, -_Measurement));
run;