问题描述
**ID **Question** Answer**
1 Referral to a
1 Referral to b
1 Referral to d
2 Referral to a
2 Referral to c
4 Referral to a
6 Referral to a
6 Referral to c
6 Referral to d
我希望转置后的数据集看起来像什么
**ID **Referral to**
1 a,b,d
2 a,c
4 a
6 a,c,d
我尝试转置数据,但是结果数据集仅包含答案列中的1个响应,而不是全部。
我一直在使用的代码:
proc transpose data=test out=test2 let;
by ID;
id Question;
var Answer; run;
数据集具有成千上万的行,其中包含数十个变量,这些变量与“引用到”示例完全相同。如何使转置的宽数据集在同一单元格中包含问题的所有答案,而不仅仅是一个?任何帮助将不胜感激。
谢谢。
解决方法
在这种情况下,您可以使用以下两种方法。
第一种使用数据步骤方法,这是一个步骤。第二个更加动态,在事实之后使用PROC TRANSPOSE
+ CATX()
创建组合变量。请注意,在PREFIX
过程中使用了transpose
选项,以使变量更易于识别和连接。
*create sample data for demonstration;
data have;
infile cards dlm='09'x;
input OrgID Product $ States $;
cards;
1 football DC
1 football VA
1 football MD
2 football CA
3 football NV
3 football CA
;
run;
*Sort - required for both options;
proc sort data=have;
by orgID;
run;
**********************************************************************;
*Use RETAIN and BY group processing to combine the information;
**********************************************************************;
data want_option1;
set have;
by orgID;
length combined $100.;
retain combined;
if first.orgID then
combined=states;
else
combined=catx(',',combined,states);
if last.orgID then
output;
run;
**********************************************************************;
*Transpose it to a wide format and then combine into a single field;
**********************************************************************;
proc transpose data=have out=wide prefix=state_;
by orgID;
var states;
run;
data want_option2;
set wide;
length combined $100.;
combined=catx(',of state_:);
run;