ID 组内的 SAS 反向计数

SAS reverse count within ID group

我习惯于在一个组中创建计数变量,每次计数都向上 +1 使用:

data objective ;
set eg ;
  count + 1 ;
  by id age ;
  if first.age then count = 1 ;
run ;

但是我想做 reverse,即每个 id 组中年龄的第一个值的值为 10,随后的每一行的值为 -1前一行:

data eg ;
  input id age desire ;
  cards;
  1 5 10
  1 4 9
  1 3 8
  1 2 7
  1 1 6
  2 10 10
  2 9 9
  2 8 8
  2 7 7
  2 6 6
  2 5 5
  2 4 4
  2 3 3
  2 2 2
  2 1 1
  3 7 10
  3 6 9
  3 5 8
  3 4 7
  3 3 6
  3 2 5
  3 1 4
  ;
run;

data objective ;
set eg ;
  count - 1 ;
  by id age ;
  if first.age_ar then count = 10 ;
run ;

有没有办法做到这一点,因为 count-1 无法识别。

试试这个(解释见代码注释):

data objective ;
retain count 10; /*retain last countvalue for every observation, 10 is optional as initial value*/
set eg ;
  count=count - 1 ; /*count -1 does not work, but count=count-1 with count as retainvariable*/
  by id age notsorted;/*notsorted because age is ordered descending*/
  if first.id then count = 10 ;/*not sure why you hade age_ar here, should be id to get your desired output*/
run ;

输出:

您可以在不使用 retain 的情况下添加 -1,如下所示:

data objective;
    set eg;
    count + -1;
    by id descending age;
    if first.id then count = 10;
run;