簡體   English   中英

如何計算SAS中組中字符串變量的模式?

[英]How do I calculate the mode of a string variable within a group in SAS?

我可以使用proc sql的子查詢來計算模式,但這是最簡單的方法嗎? 該代碼通過依靠proc sqlmax函數打破聯系來處理在計算模式時可能發生的聯系。

ods html file = "sas_output.html";

data raw_data;
 input cust_id $
       category $
       amount;
datalines;
A red 72.83
A red 80.22
A blue 0.2
A blue 33.62
A blue 30.63
A green 89.04
B blue 10.29
B red 97.07
B red 68.71
B red 98.2
B red 1.79
C green 92.94
C green 0.96
C red 15.23
D red 49.94
D blue 75.82
E blue 20.97
E blue 78.49
F green 87.92
F green 32.29
;
run;

proc sql;
  create table modes as 
    select cust_id, mean(amount) as mean_amount, category as mode_category
    from (
            select *, count(1) as count from raw_data group by cust_id, category
         )
    group by cust_id
    having count=max(count)
    order by cust_id;
quit;

data modes;
    set modes;
    by cust_id;
    if first.cust_id then output;
run;

data final_data;
    merge raw_data modes;
    by cust_id;
run;

proc print data=final_data noobs;
    title "final data";
run;

ods html close;

我試圖使用這樣的proc means

proc means data=raw_data;
    class cust_id;
    var category;
    output out=modes mode=mode_category;
run;

但出現錯誤“列表中的變量類別與為此列表指定的類型不匹配”,因為proc means不支持字符變量。

SQL當然是一種很好的方法。 這是帶有雙DOW循環的數據步驟解決方案。 如果需要,您也可以在同一步驟中使用此方法計算平均值。

排序數據以便按組使用。

proc sort data=raw_data;
  by cust_id category;
run;

讀取一次數據集,並按cust_id計數每次出現的類別。 變量maxfreq存儲最高計數,變量mode使類別具有最高計數。 因為數據是按類別變量排序的,所以在平局的情況下,這將返回最高的字母值。

第二個循環將值與第一個循環的模式一起輸出。

data want(drop=freq maxfreq);
  do until (last.cust_id);
    set raw_data;
    by cust_id category;
    if first.category then freq=0;
    freq+1;
    maxfreq=max(freq,maxfreq);
    if freq=maxfreq then mode=category;
  end;
  do until (last.cust_id);
    set raw_data;
    by cust_id;
    output;
  end;
run;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM