对于R Markdown,如何显示R变量的矩阵 [英] For R Markdown, How do I display a matrix from R variable

查看:204
本文介绍了对于R Markdown,如何显示R变量的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a rmd document where I have the following

```{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中的矩阵.该怎么办?

Now I would like to instead of hard coding the LaTeX part manually, I could use the matrix from the variables A and B instead. How could this be done?

谢谢.

推荐答案

直接,您可以编写乳胶线. writeLines()cat()会有所帮助.

Straightforwardly, you can write latex line. writeLines() or cat() would be helpful.

您可以将apply(A, 1)与两步paste()结合使用.

You can use apply(A, 1) with two step paste().

  1. paste(collpase = "&"):折叠每行
  2. paste(, "\\\\"):使用\\
  3. 折叠每列
  1. paste(collpase = "&"): collapse each row
  2. paste(, "\\\\"): collapse every column with \\

然后我们可以获得矩阵的latex公式.

Then we can get the latex formula of matrix.

write_matex <- function(x) {
  begin <- "$$\\begin{bmatrix}"
  end <- "\\end{bmatrix}$$"
  X <-
    apply(x, 1, function(x) {
      paste(
        paste(x, collapse = "&"),
        "\\\\"
      )
    })
  writeLines(c(begin, X, end))
}

如果执行此功能,则write_matex(A)给出

If you conduct this function, write_matex(A) gives

$$\begin{bmatrix}
1&0 \\
3&1 \\
\end{bmatrix}$$

使用块选项{r, results = 'asis'}时,您可能会同时在pdf和html中看到矩阵.

When you use chunk option {r, results = 'asis'}, you might see the matrix in both pdf and html.

基于此功能,您可以在乳胶块中自由使用矩阵.为此,应在函数中删除$$.代替writeLines(),可以使用paste(collapse = "").

Based on this function, you might freely use matrix in latex block. For this, $$ should be removed in the function. Instead of writeLines(), paste(collapse = "") can be used.

write_matex2 <- function(x) {
  begin <- "\\begin{bmatrix}"
  end <- "\\end{bmatrix}"
  X <-
    apply(x, 1, function(x) {
      paste(
        paste(x, collapse = "&"),
        "\\\\"
      )
    })
  paste(c(begin, X, end), collapse = "")
}

在文本部分中,您可以将该功能实现为

In the text part, you can implement this function as

$$
`r write_matex2(A)` \times `r write_matex2(B)`
$$

r markdown中,带后引号的r可以附加您的r函数和变量.这样你就可以得到

In r markdown, this r with back quotation can attach your r function and variable. So you can get

如您所见,这是可重复的.

As you can see, this is reproducible.

(C <- matrix(1:10, nrow = 2))
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    1    3    5    7    9
#> [2,]    2    4    6    8   10

类似地,

$$`r write_matex2(C)` + `r write_matex2(C)`$$

这篇关于对于R Markdown,如何显示R变量的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆