Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a matrix without row and column indices

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.

like image 210
Jonas Lindeløv Avatar asked Nov 13 '14 10:11

Jonas Lindeløv


People also ask

How do you Index in matrices?

Most often, indexing in matrices is done using two subscripts—one for the rows and one for the columns. The simplest form just picks out a single element: More generally, one or both of the row and column subscripts can be vectors: A single : in a subscript position is shorthand notation for 1:end and is often used to select entire rows or columns:

How to print matrix in Python?

Outline: To print matrix in Python use – numpy. array() method, or, numpy.matrix class, or, a list comprehension + join() method; join() + map() methods

How to convert row and column subscripts to linear indices in MATLAB?

MATLAB provides a function called sub2ind that converts from row and column subscripts to linear indices. You can use it to extract the desired elements this way: A MATLAB user recently posed this question in the comp.soft-sys.matlab newsgroup: If I want to shift the rows of an m-by-n matrix A by k places, I use A (:, [n-k+1:n 1:n-k]).

What are row and column subscripts in a matrix?

More generally, one or both of the row and column subscripts can be vectors: A single : in a subscript position is shorthand notation for 1:end and is often used to select entire rows or columns: There is often confusion over how to select scattered elements from a matrix.


2 Answers

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")
like image 91
Vincent Guillemot Avatar answered Oct 01 '22 02:10

Vincent Guillemot


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
like image 26
user1981275 Avatar answered Oct 01 '22 03:10

user1981275