[R] incidence and adjacency matrix conversion

Martin Maechler maechler at stat.math.ethz.ch
Thu Dec 7 18:24:36 CET 2006


>>>>> "Phil" == Philip Leifeld <Philip.Leifeld at uni-konstanz.de>
>>>>>     on Tue, 05 Dec 2006 22:30:02 +0100 writes:

    Phil> Dear all,
    Phil> how can I convert an m x n incidence matrix into an m x m adjacency 
    Phil> matrix or an n x n adjacency matrix? The current matrix contains binary 
    Phil> data, hence the new matrix would contain counts of common occurrences.

You have not given a self contained reproducible example
which would even be useful in such a case..

But just to be sure that the solution is not as simple as I
thought it was -- namely I thought, that for binary matrices,
crossprod()  and tcrossprod() would give what you'd want :

> n <-   10 ; m <- 4
> set.seed(1)
> M <- matrix(as.logical(rbinom(n*m, size=1, prob = 0.3)), n,m)
> symnum(M)
             
 [1,] . . | .
 [2,] . . . .
 [3,] . . . .
 [4,] | . . .
 [5,] . | . |
 [6,] | . . .
 [7,] | | . |
 [8,] . | . .
 [9,] . . | |
[10,] . | . .
> print.table(A.1 <- tcrossprod(M), zero = ".")
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    .    .    .    .    .    .    .    1     .
 [2,]    .    .    .    .    .    .    .    .    .     .
 [3,]    .    .    .    .    .    .    .    .    .     .
 [4,]    .    .    .    1    .    1    1    .    .     .
 [5,]    .    .    .    .    2    .    2    1    1     1
 [6,]    .    .    .    1    .    1    1    .    .     .
 [7,]    .    .    .    1    2    1    3    1    1     1
 [8,]    .    .    .    .    1    .    1    1    .     1
 [9,]    1    .    .    .    1    .    1    .    2     .
[10,]    .    .    .    .    1    .    1    1    .     1
> print.table(A.2 <-  crossprod(M), zero = ".")
     [,1] [,2] [,3] [,4]
[1,]    3    1    .    1
[2,]    1    4    .    2
[3,]    .    .    2    1
[4,]    1    2    1    3
> 


    Phil> Thank you for your help.

you're welcome (if it did help).

Martin Maechler, ETH Zurich




More information about the R-help mailing list