SAS 中的条件概率 Table

Conditional Probability Table in SAS

我在 SAS 工作,试图创建条件概率 table。

table 的当前结构是:5 列 x 10 行 --> 每个单元格中的值都是二进制的。 Current Data Table

col1    col2    col3    col4    col5
1   0   1   0   0
0   0   0   1   1
0   0   0   0   0
1   0   0   0   0
1   0   0   0   1
0   1   0   0   0
0   1   0   1   0
1   1   1   1   0
1   0   1   0   1
1   0   1   0   0

我想创建一个 table,每个列与其他列的条件概率。 Ideal Output

--- col1    col2    col3    col4    col5
col1    1.0 0.3 1.0 0.3 0.7
col2    0.2 1.0 0.3 0.7 0.0
col3    0.7 0.3 1.0 0.3 0.3
col4    0.2 0.7 0.3 1.0 0.3
col5    0.3 0.0 0.3 0.3 1.0

这是我正在处理的实际问题的一个更简单的版本(数百行和数百万列,所以我最好有一个可以根据 table 的大小进行调整的解决方案).

我一直在使用数组和 do 循环,但没能走多远。

我当前的代码如下所示(尚未完成):

data ideal_output;
    set binary_table;
    array obs(10,5);
    array output(5,5);
    do i=1 to 5;
        do j=1 to 5;
            do k=1 to 10;
                do l=1 to 10;
        output(m,n) = sum(obs(k,i)*obs(l,j))/sum(obs(k,i));
    end;end;end;end;
run;

您的想法是正确的 - 棘手的部分是将所有变量加载到适当的数组中。如果您的完整数据集太大而无法放入内存,您可能需要一次处理其中的一个子集。

data have;
/*Set length 3 for binary vars to save a bit of memory later*/
length col1-col5 3;
input col1-col5;
cards;
1   0   1   0   0
0   0   0   1   1
0   0   0   0   0
1   0   0   0   0
1   0   0   0   1
0   1   0   0   0
0   1   0   1   0
1   1   1   1   0
1   0   1   0   1
1   0   1   0   0
;
run;

%let NCOLS = 5;
%let NOBS = 10;

data want;
    if 0 then set have;
    array obs[&NOBS,&NCOLS];
    array p[&NCOLS];
    array col[&NCOLS];

    /*Use a DOW-loop to populate the 2-d array*/
    do _n_ = 1 by 1 until (eof);
        set have end = eof;
        do i = 1 to &NCOLS;
            obs[_n_,i] = col[i];
        end;
    end;

    do i=1 to &NCOLS;
        do j=1 to &NCOLS;
            x = 0;
            y = 0;
            do k=1 to &NOBS;
                x + obs[k,i]*obs[k,j];
                y + obs[k,j];
            end;
            p[j] = x / y;
        end;
        output;
    end;
    keep p1-p5; 
run;

您或许可以用摘要过程做一些等效的事情。这会有点混乱,因为您可能需要进行一些转置并删除“0”行,但这也许会让您开始吗?

proc tabulate data=have out=want;
  class col1-col5;
  tables (col1-col5),(col1-col5)*colpctn/printmiss misstext='0';
run;

data want_fortran;
  set want;
  if sum(of col1-col5) = 2;
run;

然后您可以使用填充 col1-col5 的哪些列来生成 column/row 名称并转置数据集。