简体   繁体   English

在SAS中使用多个变量进行转置

[英]transpose with multiple variables in SAS

In SAS, I have column variables in sequence with corresponding column variables stacked side by side, such as the following: 在SAS中,我按顺序列出列变量,并列相应的列变量,如下所示:

 id lab1 lab2 lab3 dt1  dt2  dt3  bili1 bili2 bili3 alb1 alb2 alb3
 3  dx   sx   sx   2/04 2/06 3/08 x.x   x.x   x.x   x.x  x.x  x.x 
 4  dx   tx   tx   5/05 3/06 9/06 x.x   x.x   x.x   x.x  x.x  x.x 

and I want to transpose to the following long format: 我想转换成以下长格式:

 id lab dt   bili alb
 3  dx  2/04 x.x  x.x
 3  sx  2/06 x.x  x.x
 3  sx  3/08 x.x  x.x
 4  dx  5/05 x.x  x.x
 4  tx  3/06 x.x  x.x
 4  tx  9/06 x.x  x.x

but I can't seem to manipulate this correctly, by putting 但我似乎无法通过推杆正确操纵这一点

var lab1-lab3 dt1-dt3 bili1-bili3 alb1-alb3;

there's actually no difference between that and 实际上和那之间没有什么区别

var lab1-alb3

so each column is treated independently, but I'd like to cluster these so SAS knows they have individual columns in the long dataset. 因此每个列都是独立处理的,但是我想对它们进行聚类,因此SAS知道它们在长数据集中有各自的列。 Some forums have advised me to just perform the transpose several times and merge the output data. 有些论坛建议我多次执行转置并合并输出数据。 This seems inelegant, inefficient, hard to read, and tedious... more so than SAS is on its own. 这看起来不那么优雅,效率低下,难以阅读,而且乏味......比SAS更独立。 Is there no syntax to perform this in a single data or proc step? 在单个数据或proc步骤中是否没有语法来执行此操作?

You're not going to get there with PROC TRANSPOSE without a lot of extra work. 如果没有大量的额外工作,你不会用PROC TRANSPOSE到达那里。 Most of the time, Wide to Long is easier handled within the data step. 大多数情况下,在数据步骤中更容易处理从宽到长。 In this case you can do it very easily with arrays. 在这种情况下,您可以使用数组轻松完成。

data have;
input id lab1 $ lab2 $ lab3 $ dt1 $ dt2 $ dt3 $ 
      bili1 $ bili2 $ bili3 $ alb1 $ alb2 $ alb3 $;
datalines;
 3  dx   sx   sx   2/04 2/06 3/08 x.x   x.x   x.x   x.x  x.x  x.x 
 4  dx   tx   tx   5/05 3/06 9/06 x.x   x.x   x.x   x.x  x.x  x.x 
;;;;
run;

data want;
set have;
array labs lab1-lab3;
array dts dt1-dt3;
array bilis bili1-bili3;
array albs alb1-alb3;

do _t = 1 to dim(labs);
  lab = labs[_t];
  dt  = dts[_t];
  bili= bilis[_t];
  alb = albs[_t];
  output;
end;
keep id lab dt bili alb;
run;

You could do it in a single data step, wrapped in a macro, like this: 您可以在单个数据步骤中执行此操作,包含在宏中,如下所示:

%macro trans;

data want(keep = id lab dt bili alb);
set have;
%do i = 1 %to 3;
    lab = lab&i;
    dt = dt&i;
    bili = bili&i;
    alb = alb&i;
    output;
%end;
run;

%mend;

%trans; run;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM