【问题标题】:SAS: converting narrow to wide datasetSAS:将窄数据集转换为宽数据集
【发布时间】:2016-12-16 18:36:05
【问题描述】:

我正在做 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 值,而是跳到下一行以显示在观察中找到的第二个值。

任何帮助将不胜感激。

注意:我不允许发布另一个指向我的输出的链接。

【问题讨论】:

  • 您需要使用 RETAIN 来跨行保留变量。否则,在每一行上,数组变量都设置为缺失。您还需要一个显式的 OUTPUT 语句。

标签: database-design sas data-analysis


【解决方案1】:

如前所述,您需要设置一个保留语句以将您的值传递到下一行,因为 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;

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 2014-03-07
    • 1970-01-01
    • 2020-08-11
    • 2011-04-12
    • 2015-11-28
    相关资源
    最近更新 更多