Re: [R] About the display of matrix

From: Martin Maechler <maechler_at_stat.math.ethz.ch>
Date: Tue 26 Sep 2006 - 08:28:41 GMT

>>>>> "SQW" == S Q WEN <randsnews@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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Tue Sep 26 18:31:10 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 26 Sep 2006 - 09:30:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.