我需要将行转换为SAS中的列。我的问题几乎与这个问题相同:将数据库行转换为列
主要区别是我需要使用数组来做到这一点。我不确定如何处理。我已经看了转置,但这并不符合我的问题的标准。感谢有关如何开始这个问题或如何解决问题的任何建议。
谢谢。
编辑:
Data old;
input id year cost;
datalines;
1 1998 20
1 1999 30
1 2000 40
2 1998 20
2 1999 21
2 2000 25
3 1998 32
3 1999 33
;
run;
data want;
set old;
by ID;
array allcost(3) c1 - c3;
retain c1-c3;
if first.id then i=1;
else i+1;
allcost(3) = cost;
if last.id;
run;
我想要的是:
1998 1999 2000
1 20 30 40
2 20 21 25
3 32 33
我没有获得此结果,而是在C3列中获得成本列表。我究竟做错了什么?请注意,C1-C3代表年。
看起来您有正确的想法,但是您在c3
列中唯一获得值,因为语句allcost(3)
仅指向数组中的第三位置,因此您需要使用的值i
作为索引。
让我们对您的代码进行小修改,看看会发生什么。
data new;
set old;
by id;
retain _1998-_2000(drop=year cost i);
array costs(3) _1998-_2000;
if first.id then i = 1;
else i + 1;
costs(i) = cost; * Adding the 'i' index will point to the correct cost variable.;
if last.id then output; * This will output the array as a row.;
run;
此代码似乎很近,但让我们检查一下OUPUT。
id _1998 _1999 _2000
1 20 30 40
2 20 21 25
3 32 33 25
_2000
的第三行除外的所有外观。这是因为_2000
的值从未在最后一个副组中取代。为了解决此问题,我们可以在每个副组的开头清除数组。
data new(drop=year cost i j);
set old;
by id;
retain _1998-_2000;
array costs(3) _1998-_2000;
if first.id then do;
do j = 1 to 3;
costs(j) = .; * set each value in array to missing.;
end;
i = 1;
end;
else i + 1;
costs(i) = cost;
if last.id then output;
run;
现在结果数据集看起来正确。
id _1998 _1999 _2000
1 20 30 40
2 20 21 25
3 32 33 .