2017-06-26 22 views
-1

我需要將行轉換爲SAS中的列。我的問題幾乎與此相同: Convert Database Rows into ColumnsSAS行分欄

主要區別在於我需要使用數組來完成此操作。我不完全確定如何解決這個問題。我看過TRANSPOSE,但這並不符合我的問題標準。希望得到關於如何開始這個問題的任何建議,或者如何處理它。

謝謝。

編輯:

Data old; 
input id year cost; 
datalines; 
1 1998 20 
1 1999 30 
1 2000 40 
2 1998 20 
2 1999 21 
2 2000 25 
3 1998 32 
3 1999 33 
; 
run; 

data want; 
set old; 
by ID; 
array allcost(3) c1 - c3; 
retain c1-c3; 
if first.id then i=1; 
else i+1; 
allcost(3) = cost; 
if last.id; 
run; 

我想這是什麼樣子:

 1998 1999 2000 

1  20 30 40 
2  20 21 25 
3  32 33 

非但沒有這個結果,我得到的C3列費用的清單。我究竟做錯了什麼? 請注意,c1-c3代表年份。

+1

對於旋轉的表,['PROC TRANSPOSE'](http://support.sas.com/documentation/cdl/en/proc/70377/HTML/default/viewer.htm#p1r2tjnp8ewe3sn1acnpnrs3xbad.htm)確實回答了這個問題。 你正在談論數組,但你還沒有告訴我們爲什麼。很可能,您需要查看['PROC TABULATE'](http://support.sas.com/documentation/cdl/en/basess/68381/HTML/default/viewer.htm#n1k5pgl78tt14pn19adlvtvyw8l1.htm) 。 – Code4R7

+0

謝謝,我不太清楚在哪裏需要使用數組來實現該結果,因爲我需要回答的問題沒有指定,因此造成了混淆。 – buffalol

+0

請發佈一些示例數據,以及您嘗試生成的輸出數據集的示例,這兩個示例都是在您的問題中鍵入的文本,也許這將使proc轉置是否合適更清晰? – user667489

回答

2

看起來你有正確的想法,但你只能在c3列獲取值,因爲聲明allcost(3)只指向第三位置的數組中,所以你需要使用的i值作爲索引。

讓我們對你的代碼做一個小的修改,看看會發生什麼。

data new; 
set old; 
by id; 
retain _1998-_2000(drop=year cost i); 
array costs(3) _1998-_2000; 
if first.id then i = 1; 
else i + 1; 
costs(i) = cost;   * Adding the 'i' index will point to the correct cost variable.; 
if last.id then output; * This will output the array as a row.; 
run; 

此代碼似乎變得非常接近,但讓我們檢查輸出。

id _1998 _1999 _2000 

1  20  30  40 
2  20  21  25 
3  32  33  25 

一切看起來都在這裏除了第三排爲_2000。這是因爲_2000的值從未在最後一個小組中被替換。爲了解決這個問題,我們可以在每個分組的開頭清除數組。

data new(drop=year cost i j); 
set old; 
by id; 
retain _1998-_2000; 
array costs(3) _1998-_2000; 
if first.id then do; 
    do j = 1 to 3; 
     costs(j) = .; * set each value in array to missing.; 
    end; 
    i = 1; 
end; 
else i + 1; 
costs(i) = cost; 
if last.id then output; 
run; 

現在生成的數據集看起來是正確的。

id _1998 _1999 _2000 

1  20  30  40 
2  20  21  25 
3  32  33  . 
+0

非常感謝! – buffalol

+0

@J_Lard優秀的答案 - 我希望有一種方法來收藏回答。不知道爲什麼不在那裏... –