SAS:在Proc Transpose中使用Do / Loop

时间:2016-01-08 18:21:57

标签: sas transpose

我对SAS中的Do Loops不是很熟悉,并希望得到一些帮助。我的数据看起来像这样:

产品A:1

产品A:2

产品A:4

我想转置(简单)并标记产品A:3缺失,但由于产品数量很大,我需要迭代地执行第i个程度。

如果我在SAS中运行转置部分,我的第一列将是1,第二列将是2,第三列将是4 - 但我真的希望第三列丢失,第四列是4。

有什么想法?感谢。

2 个答案:

答案 0 :(得分:0)

获取一些样本数据:

proc sort data=sashelp.iris out=sorted;
  by species;
run;

确定我们需要转置的最大列。根据您的具体情况,您可能只想使用%let max=somevalue;语句对此值进行硬编码:

proc sql noprint;  
  select cats(max(sepallength)) into :max from sorted;
quit;

%put &=max;

使用数据步骤转置数据:

data want;
  set sorted;
  by species; 
  retain _1-_&max;

  array a[1:&max] _1-_&max;

  if first.species then do;
    do cnt = lbound(a) to hbound(a);
      a[cnt] = .;
    end;
  end;

  a[sepallength] = sepallength;

  if last.species then do;
    output;
  end;

  keep species _1-_&max;
run;

请注意,我们正在定义一个列数组:_1,_2,_3,..._max。这发生在我们的array声明中。

然后,我们使用分组处理一次为单个物种填充这些新创建的列。对于每个物种,在第一个记录上,我们清除阵列。对于物种的每个记录,我们填充数组的适当元素。物种输出的最终记录数组内容。

答案 1 :(得分:0)

您需要一种方法告诉SAS您有4种产品,其值为1-4。在这个例子中,我使用所需信息创建虚拟ID,然后使用ID语句进行转置,以使用product的值命名新变量。

data product;
   input id product @@;
   cards;
1 1 1 2 1 4
2 2 2 3
;;;;
   run;
proc print;
   run;
data productspace;
   if 0 then set product;
   do product = 1 to 4;
      output;
      end;
   stop; 
   run;
data productV / view=productV;
   set productspace product;
   run;
proc transpose data=productV out=wide(where=(not missing(id))) prefix=P;
   by id;
   var product;
   id product;
   run;
proc print;
   run;

enter image description here