在数学或方程式环境中将 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?:
egin{bmatrix}
2 & 12\
3 & 17\
5 & 10\
7 & 18\
9 & 13
end{bmatrix}
理想情况下,报告代码应如下所示:
Ideally the report code would be something in the lines of:
egin{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}
",
do.call(print.xtable, calling_args),
"\end{bmatrix}
")
}
似乎做你正在寻找的东西
Seems to do what you are looking for
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)
## egin{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)
## egin{bmatrix}
## 2 & 12 \
## 3 & 17 \
## 5 & 10 \
## 7 & 18 \
## 9 & 13 \
## end{bmatrix}
这篇关于在数学或方程式环境中将 R 矩阵转换为 LaTeX 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!