如何标记同一ID与日期下结果不同的SAS观测值?
解决方案
方法1:PROC SQL 简洁实现
通过分组统计每个ID+Dt组合下result的不同取值数量,直接生成标记变量:
proc sql; create table test_marked as select t.*, case when count(distinct result) > 1 then 1 else 0 end as has_diff_result from test t group by ID, Dt order by ID, Dt; quit;
生成的has_diff_result变量中,1代表该ID+Dt组合内存在不同的result值,0代表取值完全一致。
方法2:DATA步 BY组处理
先排序保证分组逻辑正常,再通过BY组计算每组的最小/最大result值,判断是否存在差异:
/* 先按ID和Dt排序,确保BY组逻辑生效 */ proc sort data=test; by ID Dt; run; data test_marked; set test; by ID Dt; /* 保留当前组的最小、最大result值 */ retain min_result max_result; if first.Dt then do; min_result = result; max_result = result; end; else do; min_result = min(min_result, result); max_result = max(max_result, result); end; /* 标记差异:最小≠最大则为1 */ has_diff_result = (min_result ne max_result); /* 组结束后清空临时变量,避免干扰下一组 */ if last.Dt then call missing(min_result, max_result); run;
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

