SAS中If-Then语句多OR条件构建变量出错问题排查
代码错误排查与修正(构建food_ins/house_ins变量)
一、food_ins变量的问题与修正
错误点:
- 所有含
OR的条件写法逻辑错误,未对每个变量单独做值判断。原代码中worry_food_t0 OR food_didnt_last_t0 in (...)的逻辑是:只要worry_food_t0为非0、非缺失值,就会触发该条件,完全忽略food_didnt_last_t0的判断,和“任一条件满足即判定无保障”的需求不符。
修正后的代码:
/* 任一变量为无效/缺失值,food_ins设为缺失 */ if worry_food_t0 in (-99,-88,.) OR food_didnt_last_t0 in (-99,-88,.) then food_ins=.; /* 任一变量满足1/2(无保障标准),food_ins设为1 */ else if worry_food_t0 in (1,2) OR food_didnt_last_t0 in (1,2) then food_ins=1; /* 两个变量都为3(有保障),food_ins设为0 */ else if worry_food_t0=3 AND food_didnt_last_t0=3 then food_ins=0;
注:最后一行将OR改为AND,因为若其中一个变量是3、另一个是1/2,第二行条件已触发,只有两个变量均为3时才判定为有保障。
二、house_ins变量的问题与修正
错误点:
- 第一个条件的括号逻辑完全错误:
(变量1 OR 变量2 OR 变量3 OR 变量4) in (...)是把四个变量的布尔结果(0或1)组合后判断是否在无效值列表里,而布尔值不可能等于-99/-88/-77,导致该条件永远不会触发,变量含无效值时无法正确设为缺失,进而进入后续条件产生错误赋值。
修正后的代码:
/* 任一变量为无效/缺失值,house_ins设为缺失 */ if housed_where_t0 in (-99,-88,-77,.) OR living_where_t0 in (-99,-88,-77,.) OR rent_mortgage_t0 in (-99,-88,-77,.) OR living_with_others_t0 in (-99,-88,-77,.) then house_ins=.; /* 任一变量满足对应有保障标准,house_ins设为0 */ else if housed_where_t0=1 OR living_where_t0 in (3,4) OR rent_mortgage_t0=0 OR living_with_others_t0=0 then house_ins=0; /* 任一变量满足对应无保障标准,house_ins设为1 */ else if housed_where_t0 in (2,3,4,5,6) OR living_where_t0 in (1,2) OR rent_mortgage_t0=1 OR living_with_others_t0=1 then house_ins=1;
内容的提问来源于stack exchange,提问作者Evan
相关产品推荐
相关产品推荐

