假设有一个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}
但这可能很麻烦,所以我肯定会接受简单的改造.
为了将来的参考,这是我后来写的函数:
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中呈现该函数的输出.
您可以使用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}