user2957945 - 1 month ago 5x

R Question

Could someone please suggest a method to

`print`

For the matrices

`m1`

`m2`

`m1 <- m2 <- matrix(1:4, nrow=2, dimnames=list(c("a", "b"), c("d", "e")))`

Desired output

`m1 m2`

d e d e

a 1 3 a 1 3

b 2 4 b 2 4

The reason is that I have several 2x2 matrices that i am using in calculations and want to show in a Rmarkdown doc. It takes up a bit too much of the page when printing length ways. Thanks.

EDIT

My attempt at a solution

`fn <- function(x) setNames(data.frame(.=paste(" ", rownames(x)), x,`

check.names=F, row.names=NULL),c(paste(substitute(x)), colnames(x)))

cbind(fn(m1), fn(m2))

# m1 d e m2 f g

#1 a 1 3 v 1 3

#2 b 2 4 w 2 4

But this of course doesnt look very good.

Answer

A little hack-ish, but I believe it is what you want:

```
m1 <- m2 <- m3 <- m4 <- matrix(1:4, nrow=2, dimnames=list(c("a", "b"), c("d", "e")))
fn <- function(x) setNames(data.frame(.=paste("", rownames(x)), x, check.names=F, row.names=NULL),c(" ", colnames(x)))
matrix.names <- Filter( function(x) 'matrix' %in% class( get(x) ), ls(pattern = "m") )
matrix.list <- lapply(matrix.names, get)
matrix.chain <- do.call(cbind, lapply(matrix.list, fn))
cat(" ", paste0(matrix.names, collapse = " "), "\n"); print(matrix.chain, row.names = FALSE)
m1 m2 m3 m4
d e d e d e d e
a 1 3 a 1 3 a 1 3 a 1 3
b 2 4 b 2 4 b 2 4 b 2 4
```

Source (Stackoverflow)

Comments