为SAS中的每个ID查找最频繁的变量

Finding most frequent variable for each ID in SAS

我的数据集是这样的:

ID     X
769   "c"
769   "f"
769   "c"
1632  "a"
1632  "a"
1632  "b"
1632  "g"
1632  "a"

我需要的是为每个 ID 找到最频繁的 X,这样得到的数据集将是:

ID     X
769   "c"
1632  "a"

如有任何反馈,我们将不胜感激。

PROC SQL MAX() 函数作用于字符变量,因此这是一个快速的解决方案。

proc sql;
create table want as
select id, max(x) as max_a
from have
group by id;
quit;

编辑:使用 BASE SAS 和 PROC SORT 的替代解决方案。对数据进行降序排序,每个ID取第一条记录。

Proc freq data=have;
Table id*x/out=count;
 Run;

proc sort data=count;
by ID descending count;
run;

data want;
set have;
by id;
if first.id;
run;

Re-consider 使用派生的 table 子查询的 proc sql 解决方案:

proc sql;
   create table Output as   
   select id, x as freqx
   from
      (select id, x, count(x) as lettercount
       from example 
       group by id, x)  
   group by id
   having lettercount = max(lettercount);
quit;

好的,您可以使用 proc freq 和一些其他步骤来完成此操作。

首先,创建您的数据:

data have;
format id . x .;
infile datalines dsd missover dlm='|';
input id $ x $;
datalines;
769|c
769|f
769|c
1632|a
1632|a
1632|b
1632|g
1632|a
;
run;

proc sort data=have;
by id;
run;

现在我们要查看每个X for ID的频率,并将结果输出到table"almost_want"

proc freq data=have;
by id;
tables x / out=almost_want;
run;

然后我们仅对 X 具有较高计数的值进行子集化:

proc sort data=almost_want;
by id count;
run;

data want;
    set almost_want;
    by id;
    if last.id then output;
run;

OBS:我的Id变量是character,所以你要调整成你需要的。