我想知道是否可以使用sas中的proc sql有效地从宽到长转置.
我知道proc转置比我在下面建议的方法快得多.但我的目标之一是避免存储转置表.
比方说,我将table1作为
Id| A| B| C| D
_____________________
1| 100|3500|6900| 10300
2| 200| 250| 300| 350
3| 150| 32| 400| 204
4| 200| 800|1400| 2000
Run Code Online (Sandbox Code Playgroud)
我想把它变成
id|col1| col2|
______________
1| A| 100|
1| B| 3500|
1| C| 6900|
1| D| 10300|
2| A| 200|
2| B| 250|
2| C| 300|
2| D| 350|
3| A| 150|
3| B| 32|
3| C| 400|
3| D| 204|
4| A| 200|
4| B| 800|
4| C| 1400|
4| D| 2000|
Run Code Online (Sandbox Code Playgroud)
我能做到这一点;
选择id,'A'为col1,A为col2,
来自table1
,其中A~ =""
联合选择id,'B'为col1,B为col2,
来自table1
,其中B~ =""
等
但效率很低.
任何的想法?谢谢.
如果您在SAS,请使用PROC TRANSPOSE此选项.有没有特别要做到这一点很好的方式PROC SQL;,而许多SQL变种有自己的办法来转动的数据,SAS具有PROC TRANSPOSE和希望你使用它.
SAS datastep也非常有效地完成了这项工作,甚至可能更好PROC TRANSPOSE.这是一个示例,包括创建注释中所述的视图.
data want/view=want;
set have;
array vars a b c d; *array of your columns to transpose;
do _t = 1 to dim(vars); *iterate over the array (dim(vars) gives # of elements);
if not missing(vars[_t]) then do; *if the current array element's value is nonmissing;
col1=vname(vars[_t]); *then store the variable name from that array element in a var;
col2=vars[_t]; *and store the value from that array element in another var;
output; *and finally output that as a new row;
end;
end;
drop a b c d _t; *Drop the old vars (cols) and the dummy variable _t;
run;
Run Code Online (Sandbox Code Playgroud)