SAS:将行变成矩阵

时间:2018-08-06 16:19:45

标签: matrix group-by sas sas-studio

您好,我正在为一个暑期学校做项目,教书的人喜欢逐行工作。我认为将其转换为矩阵并与数组一起使用将是有益的。

当前数据集如下:

data longdata;
input var1 var2 Value;
datalines;

rowone colone 1
rowone coltwo 1
rowone colthree 2
rowone colfour 3
rowtwo colone 1
rowtwo coltwo 1
rowtwo colthree 1
rowtwo colfour 2
rowthree colone 3
rowthree coltwo 3
rowthree colthree 3
rowthree colfour 4
rowfour colone 1
rowfour coltwo 3 
rowfour colthree 3
rowfour colfour 3
;
run;

我想将以上内容转换为此,最好通过by语句:

data matrixdata;
input var1-var4;
datalines;

       colone coltwo colthree colfour
rowone       1      1      2        2
rowtwo       1      1      1        2
rowthree     3      3      3        4
rowfour      1      3      3        3
;
run;

1 个答案:

答案 0 :(得分:4)

Proc transpose非常适合将分类数据转换为其他布局形式。

proc transpose data=have out=want;
  by var1 notsorted;
  id var2;
  var value;
run;

尽管看起来像数组,但数据不是隐式数组。要在单个隐式数据步骤迭代期间成为4x4数组,传入数据集实际上将需要每行16个变量,例如v1-v16,其值为1 1 2 3 1 1 1 2 3 3 3 4 1 3 3 3。每行将对应一个数组实例。

data want2;
  retain v1-v16;
  array v (16) v1-v16;
  set have end=end;
  v(_n_) = value;
  if end;
  keep v:;
run;

data _null_;
  set want2;
  array m(4,4) v1-v16;
  do row = 1 to dim(m,1);
  do col = 1 to dim(m,2);
    put row= col= m(row,col)=;
  end;
  end;
run;