Sas 将两列合并为另外两列?
我的数据集如下所示:Sas 将两列合并为另外两列?,sas,Sas,我的数据集如下所示: weight | malf 3.18456 0 4.2433 1 3.8543 0 4.0123 1 4.15 1 我需要将此更改为: Type | respons weight 3.18456 malf 0 weight 4.2433 malf 1 weight
weight | malf
3.18456 0
4.2433 1
3.8543 0
4.0123 1
4.15 1
我需要将此更改为:
Type | respons
weight 3.18456
malf 0
weight 4.2433
malf 1
weight 3.8543
malf 0
weight 4.0123
malf 1
weight 4.15
malf 1
因此,我的数据集将是原来的两倍大。如果我已经尝试了一段时间,但我没有找到办法。
有办法做到这一点吗?这里有一个通用的解决方案,应该适合您。它将所有数值变量放入一个数组中。对于每个观察,它都会按顺序遍历所有数值变量,并执行以下操作顺序:
data want;
length Type $10.;
set have;
array numvars[*] _NUMERIC_;
do i = 1 to dim(numvars);
Type = vname(numvars[i]);
Response = numvars[i];
output;
end;
keep Type Response;
run;
这是专门用于处理输入的代码。第一个数据步骤重新创建数据。第二个输出你需要的。我假设“双倍大”是指观察次数的两倍
/*recreate input file*/
data aa;
weight =3.18456; malf= 0;
output;
weight =4.2433 ; malf= 1;
output;
weight =3.8543 ; malf= 0;
output;
weight =4.0123 ; malf= 1;
output;
weight =4.15 ; malf= 1;
output;
run;
/*output file*/
data bb;
set aa;
type="weight"; respons=weight;
output;
type="malf"; respons=malf;
output;
run;
即使使用非数值变量,该解也是有效的
- -它首先将所有变量名存储在带有PROC内容的数据集中。
- -然后为每列创建一个宏变量
- -最后,它创建输出数据集:对于每个输入行,它返回N个输出行,其中N是列数
%macro transpose_like;
/* With this step we save all the column names in the columns_dataset */
proc contents data=start_dataset out=columns_dataset(keep=name) noprint;
run;
/* With the symputx routine we save dinamically the column names to N macro variables */
data _null_;
set columns_dataset end=eof;
call symputx("Var"||strip(_N_),strip(name));
if eof then
call symputx("Var_Number",strip(_N_));
run;
/* Finally we write the output_dataset: for every row of start_dataset we output N rows */
data output_dataset(keep=var value);
length var $ 20 value $20;
set start_dataset;
%do i=1 %to &Var_Number.;
var = "&&Var&i.";
value = strip(&&Var&i.);
output;
%end;
run;
%mend transpose_like;
/* Call the macro */
%transpose_like