如何根据同一组的其他观察值为变量赋值

时间:2014-04-03 12:17:03

标签: sas

例如,如果我有个人记录的集合,组织成家庭,并且我想分配给有女儿的父母和女儿= 1的父母,并且对有个女儿的个人分配coreidentwithson = 1儿子我该怎么做?

如果给出家庭数量和关系的变量,我将如何编码 coresidentwithdaughter coresidentwithson 以获得以下结果

示例数据:

家庭 703 703 703 703 703 703 1 2 2 2 1 1 年龄 43 41 17 16 13 12 关系头配偶儿童孩子孩子 coreidentwithdaughter 1 1 0 0 0 0 coresidentwithson 1 1 0 0 0 0

家庭 704 704 704 2 2 1 年龄 29 20 2 关系头姐妹 coreidentwithdaughter 0 0 0 coresidentwithson 1 0 0

1 个答案:

答案 0 :(得分:0)

基于'child'是被视为儿子或女儿的唯一关系的假设,并且'head''spouse'是唯一允许成为父母的值(不确定你是什么)意图与'姐妹')。以下将使用PROC SQL完成工作。

proc sql;
  select t.*,
  case when t.relation in ('head','spouse') and x.son then 1 else 0 end as coresidentwithson,
  case when t.relation in ('head','spouse') and x.daughter then 1 else 0 end as coresidentwithdaughter
  table t
  inner join
  (
    select 
    household, 
    sum(case when sex=1 then 1 else 0 end) as son
    sum(case when sex=2 then 1 else 0 end) as daughter
    from table
    where relation = 'child'
    group by 1
  ) x
  on t.household=x.household;
quit;

这是自联接的示例,在执行引用回同一组的查询时需要该自联接。使用data-step也可以做到这一点,但我没有这个解决方案。

相关问题