【问题标题】:SAS software: How to delete observations with more than five zeros for the dependent variableSAS软件:如何删除因变量超过五个零的观测值
【发布时间】:2026-01-30 09:40:01
【问题描述】:

我有一个消费者面板数据,其中包含每周记录的零售店支出。唯一标识符是家庭 ID。如果支出中出现超过五个零,我想删除观察结果。也就是说,该家庭五周内没有进行任何购买。一旦确定,我将删除与家庭 ID 相关的所有观察结果。有谁知道我如何在 SAS 中实现这个过程?谢谢。

【问题讨论】:

  • 发布您尝试过的内容和样本数据。过程将是计算 0 的连续周数,识别所有超过 5 的 ID,然后删除这些 ID。可能是数据步骤或 SQL 解决方案或组合。发布示例数据以及您尝试过的内容,有人可以提供超出我一般建议的帮助。一般问题 -> 一般答案

标签: sas filtering data-cleaning


【解决方案1】:

我认为 proc SQL 在这里会很好。

这可以通过更复杂的子查询一步完成,但最好将其分解为 2 个步骤。

  1. 计算每个家庭 ID 有多少个零。

  2. 过滤以仅包含具有 5 个或更少零的家庭 ID。

proc sql;
create table zero_cnt as
select distinct household_id,
sum(case when spending = 0 then 1 else 0 end) as num_zeroes
from original_data
group by household_id;

create table wanted as
select *
from original_data   
where household_id in (select distinct household_id from zero_cnt where num_zeroes <= 5);  
quit;

编辑:

如果零必须是连续的,则构建要排除的 ID 列表的方法是不同的。

* Sort by ID and date;
proc sort data = original_data out = sorted_data;  
by household_id date;
run;  

使用 Lag 运算符:检查以前的支出金额。

在此处了解有关 LAG 的更多信息:http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000212547.htm

data exclude;   
  set sorted;   
  by household_id;    
  array prev{*} _L1-_L4;  
 _L1 = lag(spending);  
 _L2 = lag2(spending);  
 _L3 = lag3(spending);  
 _L4 = lag4(spending);  

  * Create running count for the number of observations for each ID;
  if first.household_id; then spend_cnt = 0;  
  spend_cnt + 1;  

  * Check if current ID has at least 5 observations to check. If so, add up current spending and previous 4 and output if they are all zero/missing;  
  if spend_cnt >= 5 then do;  
    if spending + sum(of prev) = 0 then output;  
  end;  
  keep household_id;
run;

然后只需使用子查询或匹配合并来删除“排除”数据集中的 ID。

proc sql;  
  create table wanted as  
  select *  
  from original_data;  
  where household_id not in(select distinct household_id from excluded);  
quit;

【讨论】:

  • 谢谢。对于以下情况,您将如何修改代码。只要我们没有连续五个零,结果变量的零计数是可以的。再次感谢。
最近更新 更多