SAS单条记录数据集特定值出现次数统计需求问询
SAS数据集特定值计数解决方案
方法1:转长表后统计
先将宽格式数据集转换为长格式,再通过proc freq统计各值的出现次数:
/* 转换为长表 */ data long; set have; array vars[*] var2-var7; /* 目标变量范围:var2到var7 */ do i = 1 to dim(vars); value = vars[i]; output; end; keep value; /* 仅保留值列 */ run; /* 统计次数并输出结果 */ proc freq data=long noprint; tables value / out=counts(rename=(count=occurrences) drop=percent); run;
方法2:原数据步直接计数
无需转表,直接在数据步中遍历变量并累计计数:
data counts; set have; length value $15.; /* 初始化计数器 */ goal_count = 0; current_state_count = 0; array vars[*] var2-var7; do i = 1 to dim(vars); if vars[i] = 'goal' then goal_count + 1; else if vars[i] = 'current_State' then current_state_count + 1; end; /* 生成目标格式的记录 */ value = 'goal'; occurrences = goal_count; output; value = 'current_State'; occurrences = current_state_count; output; keep value occurrences; run;
输出结果说明
两种方法最终都会生成包含以下内容的counts数据集:
| value | occurrences |
|---|---|
| goal | 3 |
| current_State | 3 |
内容的提问来源于stack exchange,提问作者sra
相关产品推荐
相关产品推荐

