SAS:如果Var1为空,如何将单元格内容从Var2移动到Var1

时间:2013-07-20 23:29:32

标签: sas do-while

论坛上的第一篇文章!我是一个非常基本的编程技能的业余用户,而且可悲的是词汇......

这是一个想法:对于一次观察,我有6个变量。让我们称之为Fonction1到6。

如果Fonction1为空,我希望sas将内容从Fonction2移动到Fonction1,从Fonction3移动到Fonction2等等......直到它不再为空

然后如果Fonction2为空,同样如此。

类似

观察1:9,9,BLANK,BLANK,5,4 会成为 观察1:9,9,5,4,空白,空白

请注意,整个观察结果可能是空的,这很好

所以我写了下面的代码:

    data individus_fct; 
    set individus_fct;
    do while (Fonction1 = '' and n<8);
        put n=;
        n+1;
        Fonction1 = Fonction2;
        Fonction2 = Fonction3;
        Fonction3 = Fonction4;
        Fonction4 = Fonction5;
        Fonction5 = Fonction6;
        Fonction6 = '';
    end;
    run;
data individus_fct; 
set individus_fct;
    do while (Fonction2 = '' and n<8);
        put n=;
        n+1;
        Fonction2 = Fonction3;
        Fonction3 = Fonction4;
        Fonction4 = Fonction5;
        Fonction5 = Fonction6;
        Fonction6 = '';
    end;
    run;
data individus_fct; 
set individus_fct;
    do while (Fonction3 = '' and n<8);
        put n=;
        n+1;
        Fonction3 = Fonction4;
        Fonction4 = Fonction5;
        Fonction5 = Fonction6;
        Fonction6 = '';
    end;
    run;
data individus_fct; 
set individus_fct;
    do while (Fonction4 = '' and n<8);
        put n=;
        n+1;
        Fonction4 = Fonction5;
        Fonction5 = Fonction6;
        Fonction6 = '';
    end;
    run;
data individus_fct; 
set individus_fct;
    do while (Fonction5 = '' and n<8);
        put n=;
        n+1;
        Fonction5 = Fonction6;
        Fonction6 = '';
    end;
    run;

但它不起作用......不知道为什么......(我很想知道!)

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

这里的基本概念是双数组遍历。这不是单一的最快方式,但它比稍快的选项容易得多。

data have;      *creating some random data;
array fonction[6];
do _t = 1 to 20;
do x = 1 to 6;
  if ranuni(7) < 0.7 then fonction[x]=x;  *70% chance we get a value;
end;
output;
call missing(of fonction:);          *clear out array for next time;
end;
run;

data want;
set have;
array vars fonction1-fonction6; *vars can be any name;
do _item = 1 to dim(vars); *_item is iterator, dim(vars) is count of items in vars array;
  _counter=_item+1;
  do while (missing(vars[_item]) and _counter le dim(vars)); *repeat until you get a nonmissing or you hit the last item of the array;
    vars[_item] = vars[_counter];  *make current value equal to the next value;
    vars[_counter]=.;      *set the next value to missing - it will be fixed later;
    _counter=_counter+1;   *increment iterator, or you have infinite loops!;
  end;
  if _counter > dim(vars) then leave;  *if we got to the end early, then we are done here;
end;
run;