gpt4 book ai didi

r - 对于 R Markdown,如何从 R 变量显示矩阵

转载 作者:行者123 更新时间:2023-12-04 09:44:02 26 4
gpt4 key购买 nike

我有一个 rmd 文档,其中包含以下内容

```{r code_block, echo=FALSE}
A = matrix(c(1,3,0,1),2,2)
B = matrix(c(5,3,1,4),2,2)
```

$$
\begin{bmatrix}
1 & 0 \\
3 & 1 \\
\end{bmatrix}
*
\begin{bmatrix}
5 & 1 \\
3 & 4 \\
\end{bmatrix}
$$

现在我想代替手动硬编码 LaTeX 部分,我可以使用变量 A 和 B 中的矩阵。这怎么可能?

谢谢。

最佳答案

这是 knitr::knit_print() 的完美用例.
您将找到有关 knitr::knit_print() 的详细信息其专用小插图中的方法:

vignette('knit_print', package = 'knitr')

目标是提供一个 knit_print类对象的方法 matrix .正如其他答案所建议的那样,定义运算符可能很有用。

您会在下面找到 Rmd为您的问题提供解决方案的文件。它还包含对运营商的建议。

这个答案的主要特点是你只需要写
`r A`

以 LaTeX 内联模式输出矩阵 A(没有 $ 输入)并写入
```{r echo=FALSE}
A
```

以 LaTeX 显示模式写入。

我还建议你定义一个 %times%运算符(operator)。因此,您只需编写:
`r A %times% B`

这个答案非常通用,您应该能够将其扩展到其他对象。
---
title: "R Markdown: Display a Matrix for R Variable"
author: "Romain Lesur"
output:
html_document:
keep_md: true
---

```{r setup, include=FALSE}
# Define a generic method that transforms an object x in a LaTeX string
as_latex = function(x, ...) {
UseMethod('as_latex', x)
}

# Define a class latex for LaTeX expressions
as_latex.character = function(x) {
structure(
paste(x, collapse = ' '),
class = c('latex', 'character')
)
}

# A character string of class latex is rendered in display mode
# Define a knit_print() method for the latex class
knit_print.latex = function(x, ...) {
knitr::asis_output(
paste0('$$', x, '$$')
)
}

# Now, define a method as_latex for matrix
as_latex.matrix = function(x, ...) {
as_latex(c(
'\\begin{bmatrix}',
paste(
t(x),
rep(c(rep('&', nrow(x) - 1), '\\\\'), ncol(x)),
collapse = ''
),
'\\end{bmatrix}'
))
}

# Indicate to knitr that matrix are rendered as latex
knit_print.matrix = function(x, ...) {
knitr::knit_print(as_latex(x))
}

# Build a knitr inline hook to display inline latex in inline mode
default_inline_hook = knitr::knit_hooks$get('inline')
knitr::knit_hooks$set(inline = function(x) {
x = paste(gsub('\\$\\$', '$', x))
default_inline_hook(x)
})
```


```{r}
A = matrix(c(1,3,0,1),2,2)
B = matrix(c(5,3,1,4),2,2)
```


Now, matrix are rendered as LaTeX:

Matrix A in inline mode: `r A`

Matrix A in display mode:

```{r echo=FALSE}
A
```


### Operators

As other answers suggested, it could be useful to define operators.
With the previous class, it is relatively straightforward:

```{r operators, include=FALSE}
`%times%` = function(x, y) {
as_latex(sapply(list(x, '\\times', y), as_latex))
}

`%add%` = function(x, y) {
as_latex(sapply(list(x, '+', y), as_latex))
}
```

Example in inline mode: `r A %add% A %times% B`

Display mode:
```{r echo=FALSE}
A %times% B
```

关于r - 对于 R Markdown,如何从 R 变量显示矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45591286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com