多个矩阵的打印方法

有人可以建议一种方法在终端窗口中并排打印几个矩阵.

对于矩阵m1和m2,我想要下面的所需输出.

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

期望的输出

m1      m2  
  d e     d e
a 1 3   a 1 3
b 2 4   b 2 4

原因是我有几个2×2矩阵,我在计算中使用,并希望在Rmarkdown文档中显示.打印长度时,它占用的页面太多了.谢谢.

编辑

我尝试解决方案

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

但这当然看起来不太好.

最佳答案 有点黑客,但我相信这是你想要的:

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
点赞