在数学或方程式环境中将R矩阵转换为LaTeX矩阵 [英] Converting R matrix into LaTeX matrix in the math or equation environment
问题描述
假设存在一个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表示形式?:
I am writing a report featuring LaTeX equations, using the Markdown-pandoc-LaTeX workflow. x
is one of the matrices that need to appear in these equations. Is it possible to programmatically render the LaTeX respresentation of the matrix as follows?:
\begin{bmatrix}
2 & 12\\
3 & 17\\
5 & 10\\
7 & 18\\
9 & 13
\end{bmatrix}
理想情况下,报告代码应为:
Ideally the report code would be something in the lines of:
\begin{displaymath}
\mathbf{X} = `r whatever-R-code-to-render-X`
\end{displaymath}
但这可能很麻烦,因此我一定会接受简单的转换.
but this is probably cumbersome, so I will surely settle for the simple transformation.
推荐答案
您可以将xtable包print.xtable方法与一个简单的包装器脚本一起使用,以设置一些默认参数.
You can use the xtable packages print.xtable method with a simple wrapper script to set some default 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}
并且不使用小数位,例如您的示例.
And to use no decimal places like your example.
bmatrix(x, digits=0)
## \begin{bmatrix}
## 2 & 12 \\
## 3 & 17 \\
## 5 & 10 \\
## 7 & 18 \\
## 9 & 13 \\
## \end{bmatrix}
这篇关于在数学或方程式环境中将R矩阵转换为LaTeX矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!