SAS:将窄数据集转换为宽数据集
问题描述:
我正在从SAS编程2教科书中进行练习。SAS:将窄数据集转换为宽数据集
我试图将此数据转换:
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值,而是跳到下一行显示观察中发现的第二个值。
任何帮助将不胜感激。
注意:我不允许发布另一个链接到我的输出看起来像。
答
正如已评论的那样,您需要设置一个保留语句以将您的值传送到下一行,因为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;
您需要使用RETAIN来保持跨行的变量。否则,在每一行中,数组变量都被设置为丢失。你还需要一个明确的OUTPUT语句。 – Reeza