【问题标题】:SAS adding an incremental counter based on a conditionSAS根据条件添加增量计数器
【发布时间】:2021-09-12 23:14:38
【问题描述】:

我在 SAS 中有以下数据集

Id   date        order   amount
101  5/20/2020     1       25
101  5/20/2020     2       25
101  5/20/2020     3        0
101  5/21/2020     1       25
101  5/21/2020     2       25

我需要根据‘Id’、‘Date’和‘Order’添加一个counter only amount=25

Id   date        order   amount  Ctr
101  5/20/2020     1       25   1
101  5/20/2020     2       25   2
101  5/20/2020     3        0   0
101  5/21/2020     1       25   1
101  5/21/2020     2       25   2

代码:

Data want:
Set have;
By id date order;
Ctr+1;
If first.id and first.date and first.order) and amount=25 then ctr=1;
Run;

我没有得到想要的结果。任何帮助表示赞赏。

【问题讨论】:

  • 您已经有一个订单变量,您可以利用它吗? if amount = 0 then ctr=0;?

标签: if-statement sas counter increment


【解决方案1】:

如果您出于某种原因无法利用 order 变量,这可能会起作用。我怀疑如果您的案件变得更复杂,它可能会中断。

  • 在每个日期的第一天将计数器设置为 0 或金额为 不是 25 岁。
  • 否则,如果数量为 25,则增加计数器。
data have;
input Id $  date mmddyy10.       order   amount;
cards;
101  5/20/2020     1       25
101  5/20/2020     2       25
101  5/20/2020     3        0
101  5/21/2020     1       25
101  5/21/2020     2       25
;;;


data want;
set have;
by id date ;
if first.date or amount ne 25 then ctr=0;
if amount=25 then ctr+1;
run;

proc print data=want;
run;

结果:

Obs Id  date    order   amount  ctr
1   101 22055   1   25  1
2   101 22055   2   25  2
3   101 22055   3   0   0
4   101 22056   1   25  1
5   101 22056   2   25  2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多