[R] A co-occurrence matrix

Martin Maechler maechler at stat.math.ethz.ch
Tue Nov 11 17:40:12 CET 2003


>>>>> "AndyL" == Liaw, Andy <andy_liaw at merck.com>
>>>>>     on Tue, 11 Nov 2003 07:41:18 -0500 writes:

    AndyL> Does the following help?

    > group <- c(1, 2, 1, 1, 3)
    > outer(group, group, "==")
	  [,1]  [,2]  [,3]  [,4]  [,5]
    [1,]  TRUE FALSE  TRUE  TRUE FALSE
    [2,] FALSE  TRUE FALSE FALSE FALSE
    [3,]  TRUE FALSE  TRUE  TRUE FALSE
    [4,]  TRUE FALSE  TRUE  TRUE FALSE
    [5,] FALSE FALSE FALSE FALSE  TRUE
    > outer(group, group, "==") + 0  # Turn it into a numeric matrix.
	 [,1] [,2] [,3] [,4] [,5]
    [1,]    1    0    1    1    0
    [2,]    0    1    0    0    0
    [3,]    1    0    1    1    0
    [4,]    1    0    1    1    0
    [5,]    0    0    0    0    1

very good.  Note that for large matrices, you can save (a factor
2 of) space by using integer instead, i.e.

 > outer(group, group, "==") + 0:0  # Turn it into a *integer* matrix.
                                ==
or (maybe easier to understand):
  
  r <- outer(group, group, "==")
  storage.mode(r) <- "integer"  ## as.integer() drop's the matrix dim()!

For nice visual output, also consider symnum()
{where the ``lower = FALSE'' is not needed anymore in R-patched
 (or R-devel) for several weeks now} :

> symnum(outer(group, group, "=="), lower = FALSE)
              
[1,] | . | | .
[2,] . | . . .
[3,] | . | | .
[4,] | . | | .
[5,] . . . . |
> 

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><




More information about the R-help mailing list