2014-07-22 48 views
1

我有一個表如下:來自不同行的數據組合成一個變量

id sprvsr phone name 
2 123 5232 ali 
2 128 5458 ali 
3 145 7845 oya 
3 125 4785 oya 

我想提出同樣的ID和相同的名字一列,sprvsr和電話在一列在一起如下:

id sprvsr  phone  name 
2 123-128 5232-5458 ali 
3 145-125 7845-4785 oya 

編輯問題: 還有一個問題 - 有關這一個。

我遵循了你展示我和工作的方式。謝謝!另一個問題是,例如:

sprvsr  name 
5232-5458 ali 
5232-5458 ali 
5458-5232 ali 

有沒有什麼辦法可以使它們以相同的順序?

回答

0

如果您需要相同順序的變量,則需要使用臨時數組並對其進行排序。這需要了解您可能擁有多少行。還要求對它進行排序。這比以前的解決方案稍微複雜一些(在之前的版本中)。

data have; 
    input id sprvsr $ phone $ name $; 
    datalines; 
2 123 5232 ali 
2 128 5458 ali 
3 145 7845 oya 
3 125 4785 oya 
4 128 5458 ali 
4 123 5232 ali 
; 
run; 

data want; 
array phones[99] $8 _temporary_; *initialize these two to some reasonably high number; 
array sprvsrs[99] $3 _temporary_; 
length phone_all sprvsr_all $200; *same; 
set have; 
by id; 
if first.id then do;    *for each id, start out clearing the arrays; 
    call missing(of phones[*] sprvsrs[*]); 
    _counter=0; 
end; 
_counter+1;      *increment counter; 
phones[_counter]=phone;   *assign current phone/sprvsr to array elements; 
sprvsrs[_counter]=sprvsr; 
if last.id then do;    *now, create concatenated list and output; 
    call sortc(of phones[*]);   *sort the lists; 
    call sortc(of sprvsrs[*]); 
    phone_all = catx('-',of phones[*]); *concatenate them together; 
    sprvsr_all= catx('-',of sprvsrs[*]); 
    output; 
end; 
drop phone sprvsr; 
rename 
    phone_all=phone 
    sprvsr_all=sprvsr;  
run; 

構造array[*]表示「該陣列的所有變量」。所以catx('-',of phones[*])表示將所有phones元素放入catx中(幸運的是,丟失的元素被catx忽略)。

+1

喬是對的,永遠不要相信'lag()'函數! ;) – DaBigNikoladze

+0

謝謝,它正好用這個代碼。但是原來沒有什麼工作是因爲我的變數。我有3個變量電子郵件電話和身份證。即使其中一個也不起作用。錯誤如下所示:錯誤:變量supervisors_pidm已被定義爲字符和數字。 錯誤:在這種情況下,電子郵件的變量類型無效。 錯誤:在這種情況下,手機的變量類型無效。 – user3780068

+0

關於主管的錯誤是你不能混合使用字符和數字,這是基本的SAS 101.其他錯誤表明你試圖以你不應該使用的方式使用數組。它是在我們使用電話的地方嗎? – Joe

0

這是一個辦法做到這一點:

data have; 
    input id sprvsr $ phone $ name $; 
    datalines; 
2 123 5232 ali 
2 128 5458 ali 
3 145 7845 oya 
3 125 4785 oya 
; 
run; 
data want (drop=lag_sprvsr lag_phone); 
    format id; 
    length sprvsr $7 phone $9; 
    set have; 
    by id; 
    lag_sprvsr=lag(sprvsr); 
    lag_phone=lag(phone); 
    if lag(id)=id then do; 
     sprvsr=catx('-',lag_sprvsr,sprvsr); 
     phone=catx('-',lag_phone,phone); 
    end; 
    if last.id then output; 
run; 

只是要注意輸入變量的可能lenghts和串聯的字符串的。輸入數據集必須按ID排序。

catx()函數刪除前導和尾隨空白並用分隔符連接。

+0

@ user3780068聽起來像你的主管變量是數字,這不是你想要的。 – Joe

+0

謝謝!我現在有這個錯誤:錯誤:變量supervisors_pidm已被定義爲字符和數字。 – user3780068

+0

@ user3780068如果sprvsr是數字,那麼將其轉換爲一個字符串,其中'sprvsr2 = put(sprvsr,8。);' – DaBigNikoladze

相關問題