[R] About the display of matrix

Martin Maechler maechler at stat.math.ethz.ch
Tue Sep 26 10:28:41 CEST 2006


>>>>> "SQW" == S Q WEN <randsnews at gmail.com>
>>>>>     on Mon, 25 Sep 2006 23:12:10 -0700 writes:

    SQW> For a matrix A, i don't want to display the zero
    SQW> elements in it , How to do with that?

(Using a fairly recent version of R)
Either use as.table() and use the print() method for "table"
explicitly, or,
if you are really working with sparse matrices, use the 'Matrix'
package:

> set.seed(1); m <- matrix(rpois(80, lambda=.8), 8,10);m
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    1    1    0    1    2    1    0    1     0
[2,]    0    0    4    0    0    1    1    1    0     0
[3,]    1    0    0    0    2    1    1    1    1     1
[4,]    2    0    1    0    1    1    2    0    1     2
[5,]    0    1    2    2    1    1    0    2    0     2
[6,]    2    0    0    0    0    1    0    0    2     0
[7,]    2    1    1    1    1    0    0    1    0     1
[8,]    1    1    0    1    0    1    0    0    2     3
> print(as.table(m), zero = ".")
  A B C D E F G H I J
A . 1 1 . 1 2 1 . 1 .
B . . 4 . . 1 1 1 . .
C 1 . . . 2 1 1 1 1 1
D 2 . 1 . 1 1 2 . 1 2
E . 1 2 2 1 1 . 2 . 2
F 2 . . . . 1 . . 2 .
G 2 1 1 1 1 . . 1 . 1
H 1 1 . 1 . 1 . . 2 3

> library(Matrix)
Loading required package: lattice
> M <- Matrix(m, sparse = TRUE)
> M
8 x 10 sparse Matrix of class "dgCMatrix"
                        
[1,] . 1 1 . 1 2 1 . 1 .
[2,] . . 4 . . 1 1 1 . .
[3,] 1 . . . 2 1 1 1 1 1
[4,] 2 . 1 . 1 1 2 . 1 2
[5,] . 1 2 2 1 1 . 2 . 2
[6,] 2 . . . . 1 . . 2 .
[7,] 2 1 1 1 1 . . 1 . 1
[8,] 1 1 . 1 . 1 . . 2 3
> 

---

Martin Maechler, ETH Zurich



More information about the R-help mailing list