2017-03-17 20 views
0

我有一個消費者面板數據,每週在零售商店記錄支出。唯一標識符是家庭ID。如果花費超過五個零,我想刪除觀察值。也就是說,這個家庭在五週內沒有購買任何東西。一旦確定,我將刪除與家庭ID相關的所有觀察結果。有誰知道我如何在SAS中實現這個過程?謝謝。SAS軟件:如何刪除具有五個以上零的因變量的觀察值

+1

發佈您嘗試過的和樣本數據。過程將計算連續0周的數量,確定所有id超過5的位置,然後刪除這些ID。可能是數據步驟或SQL解決方案或組合。發佈示例數據以及您嘗試過的內容以及有人可以幫助我超出我的一般建議。一般問題 - >一般的回答 – Reeza

回答

0

我認爲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

此處瞭解詳情: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; 
+0

謝謝。您將如何修改以下情況的代碼。只要我們連續沒有五個零,結果變量的零計數就可以。再次感謝。 – Fred

相關問題