使用SAS中的Panel数据建立治疗样本

时间:2015-11-30 16:23:51

标签: sas grouping panel-data

我的面板数据看起来像这样:

ID      year    dummy
1234    2007    0
1234    2008    0
1234    2009    0
1234    2010    1
1234    2011    1
2345    2008    0
2345    2009    1
2345    2010    1
2345    2011    1
3456    2008    0
3456    2009    0
3456    2010    1
3456    2011    1

更多的观察结果遵循相同的模式以及更多与此问题无关的变量。

我想建立一个ID的处理样本,其中虚拟变量"切换"在2010年(当年< 2010时为0,当年> = 2010时为1)。在上面的示例数据中,1234和3456将在样本中,而2345则不在。

我对SAS很新,我想我对CLASS和BY语句不够熟悉,无法弄清楚如何做到这一点。

到目前为止,我已经做到了这一点:

data c_temp;
    set c_data_full;
    if year < 2010 and dummy=0
        then trtmt_grp=1;
    else pre_grp=0;
    if year >=2010 and dummy=1
        then trtmt_grp=1;
run;

但是,这并没有对数据的面板方面做任何事情。我无法弄清楚如何只选择每年trtmt_grp为1的ID的最后一步。

感谢所有帮助!谢谢!

3 个答案:

答案 0 :(得分:3)

除非您需要将数据附加到其他行,否则不要认为您需要双DoW循环。如果每个ID只需要一行匹配,那么简单的单遍就足够了。

data want;
  set have;
  by id;
  retain grpcheck;   *keep its value for multiple passes;
  if first.id and year < 2010 then grpcheck=1;  *reset for each ID to 1 (kept);
  else if first.id and year ge 2010 then grpcheck=0;
  if (year<2010) and (dummy=1) then grpcheck=0;  *if a non-zero is found before 2010, set to 0;
  if (year >= 2010) and (dummy=0) then grpcheck=0; *if a 0 is found at/after 2010, set to 0;
  if last.id and year >= 2010 and grpcheck=1;  *if still 1 by last.id and it hits at least 2010 then output;
run;

每当你想为每个ID做一些逻辑(或者按某个变量的值对每个逻辑分组的行集合)时,你首先要设置你的标志/ etc。在if first.id语句组中。然后,根据每行修改您的标志。然后,添加一个if last.id组,当您点击最后一行时,该组会检查该标志是否仍然设置。

答案 1 :(得分:1)

我想你可能想要一个双DOW循环。第一个循环计算ID级别的TRTMT_GRP标志,第二个循环选择详细记录。

data want ;
  do until (last.id);
    set c_data_full;
    by id dummy ;
    if first.dummy and dummy=1 and year=2010 then trtmt_grp=1;
  end;
  do until (last.id);
    set c_data_full;
    by id ;
    if trtmt_grp=1 then output;
  end;
run;

答案 2 :(得分:1)

在我看来,Proc SQL可以提供一种非常简单的方法,

proc sql;
select distinct id from have
group by id
having sum(year<=2009 and dummy = 1)=0 and sum(year>=2010 and dummy=0) = 0
;
quit;
相关问题