在数学或方程环境中将R矩阵转换为LaTeX矩阵

 峰的紫色摩天轮 发布于 2023-02-08 13:57

假设有一个R矩阵x:

x <- structure(c(2, 3, 5, 7, 9, 12, 17, 10, 18, 13), .Dim = c(5L,2L), .Dimnames = list(NULL, c("X1", "X2")))

我正在使用Markdown-pandoc-LaTeX工作流程编写一份包含LaTeX方程的报告.x是需要出现在这些方程中的矩阵之一.是否有可能以编程方式呈现矩阵的LaTeX表示如下?:

\begin{bmatrix}
2 & 12\\ 
3 & 17\\ 
5 & 10\\ 
7 & 18\\ 
9 & 13
\end{bmatrix}

理想情况下,报告代码将是以下内容:

\begin{displaymath}
\mathbf{X} = `r whatever-R-code-to-render-X`
\end{displaymath}

但这可能很麻烦,所以我肯定会接受简单的改造.

2 个回答
  • 为了将来的参考,这是我后来写的函数:

    matrix2latex <- function(matr) {
    
    printmrow <- function(x) {
    
        cat(cat(x,sep=" & "),"\\\\ \n")
    }
    
    cat("\\begin{bmatrix}","\n")
    body <- apply(matr,1,printmrow)
    cat("\\end{bmatrix}")
    }
    

    它不需要外部包装.由于某种原因apply,在输出结束时产生了NULL(实际返回?).这是通过将返回body值赋给变量来解决的,否则就没有用了.下一个任务是在knitr 中的LaTeX中呈现该函数的输出.

    2023-02-08 13:59 回答
  • 您可以使用xtable包print.xtable方法和一个简单的包装器脚本来设置一些默认的args.

    bmatrix = function(x, digits=NULL, ...) {
      library(xtable)
      default_args = list(include.colnames=FALSE, only.contents=TRUE,
                          include.rownames=FALSE, hline.after=NULL, comment=FALSE,
                          print.results=FALSE)
      passed_args = list(...)
      calling_args = c(list(x=xtable(x, digits=digits)),
                       c(passed_args,
                         default_args[setdiff(names(default_args), names(passed_args))]))
      cat("\\begin{bmatrix}\n",
          do.call(print.xtable, calling_args),
          "\\end{bmatrix}\n")
    }
    

    似乎做你想要的

    x <- structure(c(2, 3, 5, 7, 9, 12, 17, 10, 18, 13), .Dim = c(5L,2L), .Dimnames = list(NULL, c("X1", "X2")))
    
    bmatrix(x)
    ## \begin{bmatrix}
    ##   2.00 & 12.00 \\ 
    ##   3.00 & 17.00 \\ 
    ##   5.00 & 10.00 \\ 
    ##   7.00 & 18.00 \\ 
    ##   9.00 & 13.00 \\ 
    ##    \end{bmatrix}
    

    并且不像你的例子那样使用小数位.

    bmatrix(x, digits=0)
    ## \begin{bmatrix}
    ##   2 & 12 \\ 
    ##   3 & 17 \\ 
    ##   5 & 10 \\ 
    ##   7 & 18 \\ 
    ##   9 & 13 \\ 
    ##    \end{bmatrix}
    

    2023-02-08 14:00 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有