【问题标题】:How do I calculate the mode of a string variable within a group in SAS?如何计算 SAS 组中字符串变量的模式?
【发布时间】:2015-05-20 08:59:52
【问题描述】:

我可以使用proc sql 中的子查询计算模式,但这是最简单的方法吗?此代码通过依赖 proc sql 中的 max 函数来处理在计算模式时可能发生的关系。

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 方法很好。这是几个步骤,但也很容易遵循。除非您的数据集很大并且您的问题是性能,否则我会保持原样。
  • @RobertPenr​​idge 我可能会坚持使用 SQL,尽管我也从下面的答案中学到了很多东西。性能不是问题,因为即使我的数据集有超过 4 亿个观察值,运行它也只需要大约 20 分钟,这对我来说很好(这是一个数据准备步骤,所以它只运行一次)。

标签: sas proc-sql


【解决方案1】:

SQL 无疑是一种很好的方法。这是一个带有双 DOW loop 的数据步骤解决方案。如果需要,您也可以在同一步骤中使用此方法计算平均值。

对数据进行排序,以便按组使用。

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;

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多