Print a matrix without row and column indices
Asked Answered
A

2

11

If I print a matrix, it is shown with row and column indices in the console. E.g.

> print(diag(3))
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

How can I suppress the column and row indices? I.e. something like this:

> print(diag(3), indices=FALSE)
1    0    0
0    1    0
0    0    1

I can see that the cwhmisc package should contain a printM function to do this according to the documentation but it is not there when I load cwhmisc. Also, this seems like something you should be able to to in base R.

Addy answered 13/11, 2014 at 10:24 Comment(2)
Question: Why do you want to do this? Printing to the console is purely for operational use; if you want the matrix "printed" to a file, there are plenty of options in things like write.table to suppress row and column names.Transonic
Answer: To quickly copy the matrix (actually a as.matrix(tabular(...))) to a paper draft without having to write/open/copy/close files and without having to manually remove the indices. Just laziness, I guess.Epistemology
M
13

The function prmatrix in the base package could work for this, it can take the arguments collab and rowlab:

prmatrix(diag(3), rowlab=rep("",3), collab=rep("",3))

 1 0 0
 0 1 0
 0 0 1
Microscopium answered 13/11, 2014 at 10:33 Comment(4)
(+1) It's funny that it is the example in the documentation :)Krahling
This adds space at the top and the left side though. The output is the same as for m <- diag(3); colnames(m) <- rownames(m) <- rep("", 3); print(m).Hambley
The documentation seems to be out of date: it references print.matrix but there doesn't appear to be any such print method in current R versions.Transonic
Thanks! I chose this answer over write.table because it keeps columns aligned and I do have characters in my matrix. Manually specifying rowlab and collab is ugly though and I tried out write.table in combination with print(...., gap=3) for this reason but couldn't get it to work. Using prmatrix(my_matrix, rowlab=rep("", nrow(my_matrix), collab=rep("", ncol(my_matrix)) is nicer for future copy-and-paste :-) You're welcome to update your answer with this.Epistemology
S
10

Another solution with function write.table

write.table(diag(3), row.names=F, col.names=F)

You can make it prettier by separating the columns with a tabulation

write.table(matrix(sample(1000,9),3,3), row.names=F, col.names=F, sep="\t")
Shirt answered 13/11, 2014 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.