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