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

Max*_*m.K 6 latex r knitr

假设有一个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")))
Run Code Online (Sandbox Code Playgroud)

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

\begin{bmatrix}
2 & 12\\ 
3 & 17\\ 
5 & 10\\ 
7 & 18\\ 
9 & 13
\end{bmatrix}
Run Code Online (Sandbox Code Playgroud)

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

\begin{displaymath}
\mathbf{X} = `r whatever-R-code-to-render-X`
\end{displaymath}
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*Jim 11

您可以使用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")
}
Run Code Online (Sandbox Code Playgroud)

似乎做你想要的

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}
Run Code Online (Sandbox Code Playgroud)

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

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


Max*_*m.K 7

为了将来的参考,这是我后来写的函数:

matrix2latex <- function(matr) {

printmrow <- function(x) {

    cat(cat(x,sep=" & "),"\\\\ \n")
}

cat("\\begin{bmatrix}","\n")
body <- apply(matr,1,printmrow)
cat("\\end{bmatrix}")
}
Run Code Online (Sandbox Code Playgroud)

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