2015-02-11 48 views
0

案例1使用數據步驟生成下一個觀察

假設數據按年份然後按月排序(數據總是有3個觀測值)。

Year Month Index 
2014 11 1.1 
2014 12 1.5 
2015 1  1.2 

我需要上個月的Index複製到新的觀察

Year Month Index 
2014 11 1.1 
2014 12 1.5 
2015 1  1.2 
2015 2  1.2 

案例2

Year從數據中刪除。所以我們只有MonthIndex

Month Index 
1  1.2 
11 1.1 
12 1.5 

數據總是從連續3個月收集。所以1是最後一個月。

不過,理想的輸出爲

Month Index 
1  1.2 
2  1.2 
11 1.1 
12 1.5 

我解決它通過創建另一數據集僅包含Month(1,2 ... 12)。然後右鍵兩次加入原始數據集。但我認爲有更優雅的方式來處理這個問題。

回答

1

情況1可以是一個直接的數據步驟。將end=eof添加到set語句以初始化變量eof,該變量在數據步驟正在讀取數據集的最後一行時返回值1。數據步驟中的輸出語句在每次迭代期間輸出一行。如果eof = 1,則運行一個do塊,使月份增加1並輸出另一行。

data want; 
    set have end=eof; 
    output; 
    if eof then do; 
    month=mod(month+1,12); 
    output; 
    end; 
run; 

對於情況2,我將切換到SQL解決方案。在月份自我加入表格,在第二個表格中增加1。如果存在,使用​​3210函數保留現有表中的值。如果不是,請使用第二個表中的值。由於跨越12月至1月的案件將產生5個月,因此使用proc sql中的outobs=選項將輸出限制爲四行,以排除不需要的第二個月份。

proc sql outobs=4; 
create table want as 
select 
    coalesce(t1.month,mod(t2.month+1,12)) as month, 
    coalesce(t1.index,t2.index) as index 
from 
    have t1 
    full outer join have t2 
    on t1.month = t2.month+1 
order by 
    coalesce(t1.month,t2.month+1) 
; 
quit; 
相關問題