2017-06-12 144 views
-1

我有一個數據組,看起來像這樣:將一行與同一數據集中的多行進行比較?

AAAAKEY C A C A A B A B C 
1  B A B A A B A B A 
3  A A B A A A A B A 
5  D A C A A B A A A 

爲了說明的目的我已超過40行和130列刪去。我想要做的是將「KEY」行與使用數組,邏輯和循環的以下行進行比較。但是,我不斷收到錯誤。在單個數據集中比較一行到多行需要哪種語句?我正在尋找的最終結果是,如果「關鍵」行中的答案與任何其他行中的答案匹配,則輸出1,否則輸出0. **編輯: 真的,我正在尋找因爲最終輸出是分別與原始數據集匹配的「矩陣」類型事物。 這將是這個樣子:

1 1 1 1 1 1 1 1 
0 1 0 1 1 1 1 0 
0 1 0 1 0 1 1 0 
0 1 1 1 1 1 0 0 

隨着第一行是關鍵行,其餘都進行了比較,鍵行的行。

我試圖啓動一個,但我完全卡住,不知道該怎麼做。

data form_a2; 
set form_a; 
array a[*] _character_; 
do i=1 to dim(a); 
if x[i] = "" 
+0

你能說明一下你想要的這個樣本數據的輸出是什麼嗎?所以你想要每行的1/0結果來說明它是否與密鑰匹配?或者,如果* any *記錄與密鑰匹配,您希望所有行的結果變量均爲1? – Quentin

+0

你在問一個沒有簡單答案的問題。從根本上講,這不是一個簡單的問題,因爲SAS是一種一次操作一行的語言;跨行操作有些困難。你需要更精確和有限的問題才能得到你所需要的。 – Joe

+0

我編輯了我的問題,並添加了我希望我的輸出看起來像。對不起,如果它仍然沒有意義。我感謝所有的幫助。 – lacymacc5552

回答

0

我認爲你需要一個更精確的問題得到你所需要的,但也許這將是一個開始。

您不能直接訪問兩行或更多行,但可以將一行中的值放入不同的一組變量中,並將變量與變量進行比較。因此,舉例來說,如果我們想採取SASHELP.CLASS大家,看看他們如何比較阿爾弗雷德(類數據集的第一個成員):

data test; 
    if _n_=1 then do; 
    set sashelp.class(rename=(age=age_key height=height_key weight=weight_key) keep=age height weight); 
    end; 
    set sashelp.class; 
    age_dif = (age - age_key); 
    height_dif = (height - height_key); 
    weight_dif = (weight - weight_key); 
run; 

當然,你可以使用數組做出,而不是指這更容易每一個都是單獨的,而且你可能不想重命名130個變量。因此,讓我們做到這一點,使用臨時數組稍微更簡單的方法:

data test; 
    if 0 then set sashelp.class; 
    array compvars[3] _temporary_; *storing the key values; 
    array numvars[*] _numeric_;  *storing the original numeric values; 
    array diff[3];     *storing the new difference values; 
    if _n_=1 then do;     *initializing COMPVARS to the first row; 
    set sashelp.class; 
    do _i = 1 to dim(numvars); 
     compvars[_i] = numvars[_i]; 
    end; 
    end; 
    set sashelp.class;     
    do _i = 1 to dim(numvars);  *now you perform the difference calc; 
    diff[_i] = numvars[_i] - compvars[_i]; 
    end; 
run; 
+0

對不起。我編輯了我的問題。我知道這不是很簡潔,但我希望編輯能讓它變得更好。謝謝! – lacymacc5552

+0

似乎我的答案應該或多或少地回答你的問題,不是嗎?顯然'diff'位有所不同,但它很容易適應?如果沒有,請解釋您還有哪些問題。 – Joe

0

請問下面的工作方式適合你?

/* generate a larger initial dataset */ 
%let n_col = 150; 
data have; 
    call streaminit(1); 
    length id 3; 
    array col_ [&n_col.] $2; 
    do id = 1 to 45; 
     do i = 1 to &n_col.; 
      col_[i] = scan("A B C D",ceil(rand('UNIFORM')*4)); 
     end; 
     output; 
    end; 
    drop i; 
run; 

/* perform comparison */ 
data want; 
    set have; 

    array col_ [&n_col.] $2 col_:; 
    array key_ [&n_col.] $2; 
    retain key_:; 
    array match_[&n_col.]; 

    /* arbitrarily choose first observation as "key", retain this array */ 
    if _N_ = 1 then do i = 1 to &n_col.; 
     key_[i] = col_[i]; 
    end; 

    /* for each compare each record to the "key" */ 
    do i = 1 to &n_col.; 
     match_[i] = ifn(key_[i] = col_[i],1,0); 
    end; 
    drop i col_: key_:; 
run; 
相關問題