2016-12-14 316 views
1

我在SAS中看起來像這樣的數據;在SAS中按日期求和多列

Date Type_1 Type_2 
4/8/2015 21654.72 . 
4/9/2015 34490.13 . 
4/9/2015 32429  . 
4/9/2015 .  24438.76 
4/9/2015 .  54043.18 
4/9/2015 .  58969.06 
4/9/2015 .  57721.01 
4/9/2015 .  46313.08 
4/10/2015 .  49974.06 
4/10/2015 .  52403.41 
4/10/2015 25260.07 . 
4/10/2015 27891.98 . 
4/11/2015 .  28130.06 
4/11/2015 24886.15 . 
4/11/2015 10407.6 . 
4/11/2015 49422.71 . 
4/11/2015 15242.28 . 
4/11/2015 .  25295.52 
4/11/2015 .  17522.67 
4/13/2015 29798.99 . 
4/13/2015 10445.17 . 
4/13/2015 23678.87 . 
4/13/2015 .  35470.87 
4/13/2015 .  33941.01 
4/13/2015 .  30206.06 
4/13/2015 .  26591.98 

我正在嘗試使用SAS數據步驟總結type_1和type_2,並按日期合併兩個列。

我已經試過這樣的代碼:

data work.data; 
    set data_consolidated; 
    by date; 

    if first.date then total_type_1=0 and total_type_2=0; 
    total_type_1 + type_1; 
    total_type_2 + type_2; 
    if last.date then output; 
    drop type_1; 
    drop_type_2; 
run; 

此代碼consilidates日期,但不是那些在日期列的所有值相加,它是將當前值到所有以前的值以累積的方式。

只是要清楚,下面是什麼,我試圖讓數據看起來像一個例子:

date  type_1  type_2 
4/8/2015 21654.72 . 
4/9/2015 66919.13 128472.85 
4/10/2015 53152.05 102377.47 
4/11/2015 99958.74 70948.25 

任何建議或幫助是極大的讚賞。

回答

2

試試這個:

proc sql; 
    select distinct date, sum(type_1) as type_1, sum(type_2) as type_2 from data_consolidated group by date; 
quit; 
+0

這是完美的。我想我已經將自己的想法設置在數據步驟上,並沒有考慮proc sql。謝謝@陳生林! – Jarom

1

我覺得你的問題是這條線。

if first.date then total_type_1=0 and total_type_2=0; 

這將導致total_type_1設置到任何一個1(真)或基於在賦值語句的右側的布爾表達式的求值0(假)。 total_type_2的值不會更改。

也許你的意思做:

if first.date then total_type_1=0; 
if first.date then total_type_2=0; 

if first.date then do; 
    total_type_1=0; 
    total_type_2=0; 
end; 

使用DOW循環是做這種類型的事情在數據步的好辦法。

data want; 
    do until(last.date); 
    set data_consolidated; 
    by date; 
    total_type_1 = sum(total_type_1,type_1,0); 
    total_type_2 = sum(total_type_2,type_2,0); 
    end; 
    drop type_1 type_2 ; 
run; 
+0

這似乎是問題所在。現在很明顯,但我沒有意識到需要將這條線分成兩部分才能正確執行。 – Jarom