SAS:将窄数据集转换为宽数据集
SAS: converting narrow to wide dataset
我正在做 SAS Programming 2 教科书中的练习。
我正在尝试转换此数据:
Narrow Data set
对于像这样的广泛数据集:
Wide Data Set
我还应该在我的数据步骤中有一个数组,并且只输出变量 customer_id 和 month1 到 month12.
我的代码如下:
Data customer_orders(keep=Customer_ID month1-month12);
set orion.order_summary;
by customer_id;
array month{12} month1-month12;
do i= 1 to 12;
if order_month = i then
month{i}= sale_amt;
end;
run;
proc print data=customer_orders;
run;
当我 运行 这段代码时,我的问题是观察不会在一次观察中显示 customer_id 的所有 sale_amt 值,而是跳到下一行显示在观察中发现的第二个值。
如有任何帮助,我们将不胜感激。
注意:我不允许 post 另一个 link 我的输出结果。
如评论所述,您需要设置保留语句以将您的值转移到下一行,因为 SAS 在处理步骤中将值重置为缺失。 Last.cust_id 然后只取每个客户 ID 的最后一行,这一行应该包含您对该客户的所有观察。
然而,这将在之后保留所有值,除非另有说明。因此,使用 first.cust_id 您可以将每个新客户 ID 的所有值都设置为缺失。
data test;
input Cust_id Month Sale_Amt;
Datalines;
5 5 478
5 6 126.8
5 9 52.50
5 12 33.8
10 3 32.60
10 1 200
;
run;
proc sort data = test out = test_sort;
by cust_id month;
run;
data test2 ( drop = month sale_amt i );
set test_sort;
by cust_id;
array holder (*) Month1-Month12;
retain Month1-Month12;
do i = 1 to 12;
if first.cust_id then holder{i} = .;
if month = i then holder{i} = sale_amt;
end;
if last.cust_id;
run;
我正在做 SAS Programming 2 教科书中的练习。
我正在尝试转换此数据:
Narrow Data set 对于像这样的广泛数据集:
Wide Data Set 我还应该在我的数据步骤中有一个数组,并且只输出变量 customer_id 和 month1 到 month12.
我的代码如下:
Data customer_orders(keep=Customer_ID month1-month12);
set orion.order_summary;
by customer_id;
array month{12} month1-month12;
do i= 1 to 12;
if order_month = i then
month{i}= sale_amt;
end;
run;
proc print data=customer_orders;
run;
当我 运行 这段代码时,我的问题是观察不会在一次观察中显示 customer_id 的所有 sale_amt 值,而是跳到下一行显示在观察中发现的第二个值。
如有任何帮助,我们将不胜感激。
注意:我不允许 post 另一个 link 我的输出结果。
如评论所述,您需要设置保留语句以将您的值转移到下一行,因为 SAS 在处理步骤中将值重置为缺失。 Last.cust_id 然后只取每个客户 ID 的最后一行,这一行应该包含您对该客户的所有观察。
然而,这将在之后保留所有值,除非另有说明。因此,使用 first.cust_id 您可以将每个新客户 ID 的所有值都设置为缺失。
data test;
input Cust_id Month Sale_Amt;
Datalines;
5 5 478
5 6 126.8
5 9 52.50
5 12 33.8
10 3 32.60
10 1 200
;
run;
proc sort data = test out = test_sort;
by cust_id month;
run;
data test2 ( drop = month sale_amt i );
set test_sort;
by cust_id;
array holder (*) Month1-Month12;
retain Month1-Month12;
do i = 1 to 12;
if first.cust_id then holder{i} = .;
if month = i then holder{i} = sale_amt;
end;
if last.cust_id;
run;