2017-09-12 84 views
0

我試圖檢測一個變量的特定值,並在滿足這些條件時創建一個新變量。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且結果存在時,它正常工作。但是如果結果缺失,那麼就會出現問題。

+0

請與您的示例代碼示例數據一致。在你的代碼中,你引用變量'visit','visitnum'和'day',這些變量不會出現在你的示例數據中。您的標誌變量在您的數據中稱爲「base」,但在您的代碼中稱爲「base_」。除此之外,從您的樣本結果和小解釋(這看起來不正確),您試圖實現的目標不明確。你的'if-then-if'語法看起來很奇怪 – user2877959

+0

哇。這段代碼被匆忙複製,甚至沒有意識到有太多的錯誤。現在我已經糾正並修改了我的問題。 – Laura

回答

2

這個問題似乎有點偏離。 「否則,如果時間=」「和時間= 1」在那裏似乎有一個錯字。

但是,您的語法看起來很穩固。我用你給定的數據做了一個例子。第一個條件起作用,但第二個條件(如果)是假設。更新爲問題已更新。

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)的旁邊。 (如果沒有,則添加更多滯後。)模擬導致函數我們將數據向後排序並利用滯後。

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

+0

對於那些4個主題是有效的,但實際上在我的數據集中有60個主題(最初沒有提及它),因此使用ID號檢測這些值會耗盡。 – Laura

+0

@Laura更新回答。 – pinegulf

+0

嗨!這將做到這一點。非常感謝你! – Laura