如何根据表中的某些条件为每条记录分配不同的单元格值?

时间:2016-03-26 19:38:15

标签: sas coding-efficiency

在给定表中的某些条件的情况下,我必须为每条记录分配不同的单元格值。

Table

在图片中column1= elig, column2=status, column3= type, column4 =metro, column5=quartile, column6=urb, column7=cell。我刚刚在if if else中写的前三个条件(它们来自另一个表)。

但是一旦我开始使用变量`quartile,urb和type,我需要一个比我写的更好的代码。

  • Metro将从1-4增加。
  • 四分位数与其他记录一起递增。
  • 键入更改为一组。

对于第一个块type = 1,对于第二个块type maybe be 4 or 5(不一定是增量)。下一个类型组可能是type 7,8,9,10

每个记录只更改单元格值。我知道我可以用宏变量代替缩短名称并保存输入但是如何使这段代码更紧凑,更高效。

非常感谢提前。

 If elig=0 then cell=0;

 else if elig =1 then 
do;
   if status in ('2','3') then cell=1;
   else if ( status = ' ' and typec=25 )  then cell =2;
    else if (status ='1','4','') and (quartile = . )  then cell=2;
end;

     else if  elig= '1' and type =1 and metro eq='1' then 
do;
       if quartile = 1 and urb in ('1','2') then cell =1111;
else if quartile = 1 and urb = '3'  then cell =1112; 
else if quartile = 2 and urb in ('1','2') then cell =1121;
else if quartile = 2 and urb = '3'  then cell =1122; 
else if quartile =3 and urb in ('1','2') then cell =1141;
else if quartile = 3 and urb = '3'  then cell =1142; 
else if quartile = 4 and urb in ('1','2') then cell =1121;
else if quartile = 4 and urb = '3'  then cell =1172; 
end;
/*here will be 3 more blocks of code for metro =2,3,4* /
/*note type changes value after metro cycles through 4 iterations*/

    else if elig='1' and  type =('4','5') and metro eq='1 then 
do;
if quartile = 1 and urb in ('1','2') then cell =1211;
else if quartile = 1 and urb = '3'  then cell =1212; 
else if quartile = 2 and urb in ('1','2') then cell =1221;
else if quartile = 2 and urb = '3'  then cell =1222; 
else  if quartile =3 and urb in ('1','2') then cell =1241;
else if quartile = 3 and urb = '3'  then cell =1242; 
else if quartile = 4 and urb in ('1','2') then cell =1271;
else if quartile = 4 and urb = '3'  then cell =1272; 
end;
/*3 more blocks of code for metro =2,3,4* /
/*then type changes and metro=1 and so on*/
else if elig='1' and type  type =('7','8') and metro eq=1 then 
    do;  
/*more code until my groups end* /
   end;

1 个答案:

答案 0 :(得分:0)

从您发布的数据看,您只需要重新编码原始变量并连接结果。

e.g。

data out_data;
    set in_data;
length class_12 $2 class_3 class_4 $1 class $4.;

select (type);
    when (1) 
     do;
        select (metro);
            when (1) class_12 = '11';
            when (2) class_12 = '12';
            when (3) class_12 = '14';
            otherwise;
        end;
     end;
    when (4, 5) 
      do;
        select (metro);
            when (1) class_12 = '21';
            when (2) class_12 = '22';
            when (3) class_12 = '24';
            otherwise;
        end;
    end;
    otherwise;
end;
select (quartile);
    when (1) class_3 = '1';
    when (2) class_3 = '2';
    when (3) class_3 = '4';
    when (4) class_3 = '7';
    otherwise;
end;
select (urb);
    when (1, 2) class_4 = '1';
    when (3) class_4 = '2';
    otherwise;
end;
class = class_12||class_3||class_4;
run; 

添加您的附加条件,如果需要,还会引入更多变量。