SAS中相同变量的多个条件

时间:2017-09-12 06:00:02

标签: if-statement sas

我正在尝试检测一个变量的特定值,并在满足这些条件时创建一个新变量。

这是我数据的一部分(我有更多行):

id time result 
1  1    normal 
1  2    normal 
1  3    abnormal 
2  1    normal 
2  2    
3  3    normal  
4  1    normal 
4  2    normal      
4  3    abnormal  
5  1    normal 
5  2    normal   
5  3             

我想要什么

id time result    base 
1  1    normal 
1  2    normal      x
1  3    abnormal 
2  1    normal      x
2  2  
2  3    normal  
3  3    normal          
4  1    normal 
4  2    normal      x
4  3    abnormal    
5  1    normal 
5  2    normal      x
5  3               

当结果存在于时间点(时间)时,应填充我的基线值(基数)2。如果没有结果,那么基线应该在时间= 1。

if result="" and time=2 then do; 
if time=10 and result ne "" then base=X; end;

if result ne "" and time=2 then base=X;  `   

当时间= 2并且结果存在时,它可以正常工作。但如果结果丢失,那就有问题了。

1 个答案:

答案 0 :(得分:2)

问题似乎有点过时了。 "否则,如果时间=""和时间= 1"那里似乎有一个错字。

但是,你的语法似乎很扎实。我已经用你给定的数据做了一个例子。第一个条件有效,但第二个条件(否则为if)是假设。更新为问题已更新。

options missing='';
    data begin;
    input id time  result $ 5-20 ;
    datalines;
    1  1    normal 
    1  2    normal 
    1  3    abnormal 
    2  1    normal 
    2  2         
    3  3    normal  
    4  1    normal 
    4  2    normal      
    4  3    abnormal 
    ;
run;

data flagged;
    set begin;
    if time=2 and result NE "" then base='X';
    else if time=1 and id=2 then base='X';
run;

根据重访的问题进行编辑。

假设时间点(1)始终位于点(2)的旁边。 (如果没有,则添加更多滞后。)模拟 Lead 功能,我们会向后排序数据并利用滞后。

proc sort data=begin; by id descending time; run;

data flagged;
    set begin;
    if lag(time)=2 and lag(result) EQ "" then base='X'; 
    if time=2 and result NE "" then base='X';
run;

有关滞后的更多信息:https://communities.sas.com/t5/SAS-Communities-Library/How-to-simulate-the-LEAD-function-opposite-of-LAG/ta-p/232151