SAS 如果前一行值在特定条件下与当前标志不匹配,则向标志添加 1

SAS Add 1 to flag if previous row value doesn't match with current flag following certain condition

我有一个正在创建的 table,我们会说第 1 列是 YearMonth,第 2 列是标志。

YearMonth Flag
200101    1
200102    1        
200103    0
200104    1
200105    1
200106    0
200107    1
200108    0

注意:标志列的第一个条目将始终为 1。

如果当前标志与前一行值不匹配以及一个主要条件(为了更好的解释,在输出后解释),我想给标志加 1。

输出应该是:

YearMonth Flag Stage
200101    1    1 
200102    1    1    
200103    0    2
200104    1    3 
200105    1    3
200106    0    4
200107    1    3 
200108    0    4

请注意只有 4 个阶段。因此,如果在第 4 阶段之后重复标志,则它不应递增,并且如果标志 = 1 则输出为阶段 = 3,如果标志 = 0.

则输出为阶段 = 4

我正在尝试这样的事情:


 data one;
 set Query;
 Stage=lag(flag);
 if first.flag then Stage=1;
 if first.flag then Stage=1;
 if flag ne Stage+1 then Stage=Stage+1;
 run;

解释为什么此代码不起作用将非常有帮助。谢谢!

此外,我知道一旦达到第 4 阶段我就不会做某事了。

stage 值需要在隐式循环的迭代之间保留。隐式 retain 将伴随 sum 语句 的使用,其语法为 <variable>+<expression>;

示例:

data have; input 
YearMonth Flag; datalines;
200101    1
200102    1
200103    0
200104    1
200105    1
200106    0
200107    1
200108    0
;

data want(drop=maxstage_reached);
  set have;
  
  if flag ne lag(flag) then stage+1;                * increment per rules;

  if stage = 4 then maxstage_reached=1;             * tracking flag (retained);

  if maxstage_reached then stage = 4 - flag;        * special rule;

  retain maxstage_reached;
run;

这本质上是对观察组进行计数。所以使用BY分组处理。在 BY 语句中添加 NOTSORTED 关键字,这样 SAS 就不会抱怨值未排序。开始新组时增加计数器。

data want;
  set have;
  by flag notsorted;
  stage + first.flag;
run;

要添加您的第二个条件,您只需添加此行

  stage = min(stage,4 - flag);