简体   繁体   English

保留SAS中组中变量的值

[英]Retain the value of a variable within a group in SAS

I want to create a variable Var2 that is equal to 1 starting at the first observation Var1 is equal to 1 and Var2 is equal to 1 until the end of the by group defined by ID. 我想创建一个变量Var2,该变量从第一个观察值开始等于1,并且Var2等于1,直到ID定义的by组的末尾为止。 Here is the minimal working example: 这是最小的工作示例:

ID Year Var1 ID年Var1
1 1 . 1 1
1 2 0 1 2 0
1 3 . 1 3。
1 4 1 1 4 1
1 5 . 1 5。

And I want to create the following output: 我想创建以下输出:

ID Year Var1 Var2 ID年Var1 Var2
1 1 . 1 1 .
1 2 0 0 1 2 0 0
1 3 . 1 3。 0 0
1 4 1 1 1 4 1 1
1 5 . 1 5。 1 1个

My current code is as follows: 我当前的代码如下:

 DATA data1;
SET data0;
BY ID YEAR ;
IF LAST.ID THEN END = _N_;
IF Var1 > 0 THEN CNT=_N_;
RUN;
DATA data2;
SET data1;
BY ID YEAR ;
Var2 = 0;
IF Var1 = 1 THEN DO;
    DO I = CNT TO END;
        Var[I] = 1; 
    END;
END;
RUN;

However, SAS does not loop along observations. 但是,SAS不会随观察结果循环。

I'm not sure what your example is doing, but this is fairly straightforward. 我不确定您的示例在做什么,但这很简单。

data want;
  set have;
  by id;
  retain var2;
  if first.id then var2=0;
  if var1=1 then var2=1;
run;

Retain var2 to keep its value across observations, and then set it to 1 when you see a 1 in var1 ; 保留var2以在各个观察中保留其值,然后在var1看到1时将其设置为1; finally, set it to 0 when you see a first.id row. 最后,在看到first.id行时将其设置为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM