How do you make a table into one long row in SAS?

喜欢而已 提交于 2019-12-11 06:35:50

问题


I have a table with a number of variables such as:

+-----------+------------+---------+-----------+--------+
| DateFrom  |   DateTo   |  Price  | Discount  |  Cost  |
+-----------+------------+---------+-----------+--------+
| 01jan17   |  01jul17   |     17  |        4  |     5  |
| 01aug17   |  01feb18   |    15   |       1   |     3  |
| 01mar18   |  01dec18   |    12   |       2   |     1  |
| ...       |  ...       |    ...  |      ...  |    ... |
+-----------+------------+---------+-----------+--------+ 

However I want to split this so I have:

+------------+------------+----------+-------------+---------+-------------+------------+----------+-------------+-------------+
| DateFrom1  |  DateTo1   |  Price1  |  Discount1  |  Cost1  |  DateFrom2  |  DateTo2   |  Price2  |  Discount2  |  Cost2 ...  |
+------------+------------+----------+-------------+---------+-------------+------------+----------+-------------+-------------+
| 01jan17    |   01jul17  |      17  |          4  |      5  |  01aug17    |  01feb18   |     15   |         1   |          3  |
+------------+------------+----------+-------------+---------+-------------+------------+----------+-------------+-------------+

回答1:


There's a cool (not at all obvious) solution using proc summary and the idgroup statement that only takes a few lines of code. This runs in memory and you're likely to come into problems if the dataset is large, otherwise this works very well.

Note that out[3] relates to the number of rows in the source data. You could easily make this dynamic by adding a prior step that calculates the number of rows and stores it in a macro variable.

/* create initial dataset */
data have;
input (DateFrom DateTo) (:date7.) Price Discount Cost;
format DateFrom DateTo date7.;
datalines;
01jan17 01jul17 17 4 5
01aug17 01feb18 15 1 3
01mar18 01dec18 12 2 1
;
run;

/* transform data into 1 row */
proc summary data=have nway;
output out=want (drop=_:) 
        idgroup(out[3] (_all_)=) / autoname;
run;


来源:https://stackoverflow.com/questions/49130605/how-do-you-make-a-table-into-one-long-row-in-sas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!