Matrix SAS 9.3:更改缺少行的矩阵形状

Matrix SAS 9.3:更改缺少行的矩阵形状,matrix,sas,sas-iml,Matrix,Sas,Sas Iml,我有以下格式的数据 P1 P2 Score A A 1 A B 2 A C 5 B B 4 B C 9 C A 3 C B 6 我想把它们变成一个3*3的矩阵,因为缺少的行是零 我在谷歌上找到了这个 但我不知道我是否缺少行,如何才能做到这一点?如果要创建表示3x3矩阵的SAS数据集,可以使用PROC TRANSPOSE从数据中创建。填写P1和P2的缺失组合,这可以通过多种方式完成。您的数据适合使用PROC SUMMARY COMP

我有以下格式的数据

P1 P2 Score  
A  A  1  
A  B  2  
A  C  5  
B  B  4   
B  C  9  
C  A  3  
C  B  6  
我想把它们变成一个3*3的矩阵,因为缺少的行是零

我在谷歌上找到了这个


但我不知道我是否缺少行,如何才能做到这一点?

如果要创建表示3x3矩阵的SAS数据集,可以使用PROC TRANSPOSE从数据中创建。填写P1和P2的缺失组合,这可以通过多种方式完成。您的数据适合使用PROC SUMMARY COMPLETETYPES的功能来填充零

data p;
   input (P1 P2)(:$1.) Score;
   cards;
A A 1
A B 2
A C 5
B B 4
B C 9
C A 3
C B 6 
;;;;
   run;
proc summary data=p completetypes nway;
   class p:;
   freq score;
   output out=filled(drop=_type_ rename=(_freq_=Score));
   run;
proc print;
   run;
proc transpose out=M3x3;
   by P1;
   id P2;
   var score;
   run;
proc print;
   run;

我可能也会在基本SAS中这样做,但在IML中也非常可行。我使用该方法将ABC转换为数值,然后使用
FULL
函数将矩阵平方:

data have;
input P1 $ P2 $ Score;
datalines;
A  A  1  
A  B  2  
A  C  5  
B  B  4   
B  C  9  
C  A  3  
C  B  6  
;;;;
run;
proc iml;

use have;
read all var _NUM_ into have_mat;
read all var _CHAR_ into p_mat;

p1_unique = unique(p_mat[,1]);  *get unique values of p1;
p2_unique = unique(p_mat[,2]);  *get unique values of p2;

num_mat = j(nrow(p_mat),3,0);   *generate empty matrix to populate;

do i = 1 to ncol(p1_unique);    *code the p1 values;
  idx = loc(p_mat[,1] = p1_unique[i]);
  num_mat[idx,2] = i;           *sparse matrix format requires 2nd col be row values;
end;

do i = 1 to ncol(p2_unique);    *code the p2 values;
  idx = loc(p_mat[,2] = p2_unique[i]);
  num_mat[idx,3] = i;           *sparse matrix format requires 3rd col be col values;
end;

  num_mat[,1] = have_mat;       *and first col is the values for the matrix itself;

final_mat = full(num_mat);      *FULL() function creates a square matrix and fills with 0s;
print final_mat;
quit;

最简单的解决方案是使用PROC FREQ中的稀疏选项来构建密集矩阵。然后,您可以将数据读入SAS/IML,并对其进行整形,使其成为方形。使用“p”作为数据集的名称(如其他答案中所示):


非常感谢你,我也让p:变成p1和p2@user131605
p:
应解析为
p1p2
<代码>:是一个通配符。
proc freq data=p noprint;
tables p1*p2 /sparse out=P2;  /* P2 is dense */
weight score;
run;

proc iml;
use p2;  read all var {Count};  close p2;
x = shape(count, sqrt(nrow(Count)));
print x;